01.API Testing With CSharp
01.API Testing With CSharp
RestSharp
SoftUni Team
Technical Trainers
Software University
https://softuni.bg
Have a Question?
sli.do
#QA-BackEnd
Table of Contents
1. Understanding APIs:
Concepts
2. Serialization and Deserialization:
JSON files
3. API Testing with C#:
GitHub API Requests
NUnit + RestSharp
Integration and API Testing
Concepts
Brief Recap on Integration Testing
Validates combined functionality of software modules
Detects interface defects, verifies data flow and
communication
Follows unit testing; precedes system testing
Applies to database integration, APIs (REST, SOAP, GraphQL),
service interactions
Objective: Ensure system integrity and seamless functionality
What is API Recap
API == Application Programming Interface
APIs serve as the intermediaries that allow two applications to
talk to each other
Set of functions and specifications that software programs and
components follow to talk to each other
API examples:
JDBC – Java API for apps to talk with database servers
Windows API – Windows apps talk with Windows OS
Web Audio API – play audio in the Web browser with JS
6
Web Services and APIs
Web services expose back-end APIs over the network
May use different protocols and data formats: HTTP, REST,
GraphQL, gRPC, SOAP, JSON-RPC, JSON, BSON, XML, YML, …
Web services are hosted on a Web server (HTTP server)
Provide a set of functions, invokable from the Web (Web API)
RESTful APIs is the
most popular Web
service standard
7
SOAP APIs
SOAP (Simple Object Access Protocol) APIs are protocol-based,
ensuring high levels of security and standardized
communication via XML
Preferred for enterprise-level web services where security and
transactional reliability are paramount
Testing Focus: Requires thorough validation of the SOAP
envelope, headers, and body, along with adherence to WS-*
standards
8
SOAP API Example
National Weather Service (NWS) SOAP-based API for weather data
http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl
Includes WSDL (Web Services Description Language) document for
describing the services offered
Operation: Get weather forecast
SOAP Action: LatLonListCityNames
Request: XML formatted SOAP envelope specifying the desired operation
and parameters(of city names or geographic coordinates)
Response: XML-formatted response (weather forecast data for
the requested locations)
9
GraphQL APIs
Defined by GraphQL (query language) that allows clients to
request exactly what they need, making it highly efficient for
data retrieval
Enables clients to define the structure of the data required,
reducing over-fetching and under-fetching issues common in
REST APIs
Testing Considerations: Emphasizes validating query responses,
handling dynamic data retrieval, and ensuring efficient
performance
10
GraphQL APIs Example
GitHub offers a GraphQL API, enabling clients to request
exactly the data they need
GraphQL queries are tailored by the requester
GraphQL API has a single endpoint:
https://api.github.com/graphql
More on GitHun GraphQL API:
https://docs.github.com/en/graphql
11
GraphQL APIs Example
Fetching a user's name and the last three issues from a repository
query {
repository(owner:"octocat", name:"Hello-World") {
issues(last:3) {
edges {
node {
title
url
}
}
}
}
}
12
RESTful APIs
Based on the Representational State Transfer architectural
style, emphasizing simplicity, statelessness, and a
uniform interface
Utilizes standard HTTP methods (GET, POST, PUT, DELETE)
for operations, making it widely adopted for web services
Offers scalability, performance, and ease of use,
with data typically exchanged in JSON or XML format
13
RESTful APIs Example
The GitHub REST API - widely used for actions like creating
repositories, fetching user data, or automating workflow processes
Base URL for GitHub API v3: https://api.github.com
Example Operation: Fetching a user's public repositories
Request Type: GET
Endpoint: /users/{username}/repos
Sample Request: GET https://api.github.com/users/octocat/repos
Retrieves data in JSON format, listing public repositories for the
specified GitHub username
14
RESTful API Testing
The process includes sending various HTTP requests to
the API endpoints and assessing the responses against
expected outcomes
Endpoints: Each URL that allows access to the API's resources
HTTP Methods: GET, POST, PUT, DELETE, etc., which define the
action on the resources
Response Status: HTTP response status codes like 200 OK,
404 Not Found, etc.
Data Exchange: Validating the request payload and
response body
15
{}
20
What is JSON.NET?
JSON.NET is a JSON framework for .NET
More functionality than built-in functionality
Supports LINQ-to-JSON
Out-of-the-box support for parsing between JSON
and XML
Open-source project: http://www.newtonsoft.com
To install JSON.NET use the NuGet Package Manager
21
General Usage
JSON.NET exposes a static service JsonConvert
Used for parsing and configuration to
Serialize an object
var jsonProduct = JsonConvert.SerializeObject(product);
Deserialize an object
var objProduct =
JsonConvert.DeserializeObject<Product>(jsonProduct);
22
Configuring JSON.NET
By default, the result is a single line of text
To indent the output string use Formatting.Indented
JsonConvert.SerializeObject(products, Formatting.Indented);
{
"pump": {
"Id": 0,
"Name": "Oil Pump",
"Description": null,
"Cost": 25.0
},
"filter": {
"Id": 0,
"Name": "Oil Filter",
"Description": null,
"Cost": 15.0
}
} 23
Configuring JSON.NET
Deserializing to anonymous types Incoming JSON
var json = @"{ 'firstName': 'Svetlin',
'lastName': 'Nakov',
'jobTitle': 'Technical Trainer' }";
var template = new
{
FirstName = string.Empty,
LastName = string.Empty, Template
JobTitle = string.Empty objects
};
var person = JsonConvert.DeserializeAnonymousType(json,
template);
24
JSON.NET Attributes
By default JSON.NET takes each property / field from the class
and parses it
This can be controlled using attributes
public class User Parse Username
{ to user
[JsonProperty("user")]
public string Username { get; set; }
[JsonIgnore] Skip the property
public string Password { get; set; }
}
25
JSON.NET Parsing of Objects
By default JSON.NET takes each property / field from the class
and parses it
This can be controlled using ContractResolver
DefaultContractResolver contractResolver =
new DefaultContractResolver()
{
NamingStrategy = new SnakeCaseNamingStrategy()
};
var serialized = JsonConvert.SerializeObject(person,
new JsonSerializerSettings()
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
26
LINQ-to-JSON
LINQ-to-JSON works with JObjects
Create from JSON string
JObject obj = JObject.Parse(jsonProduct);
Using JObject
foreach (JToken person in people)
{
Console.WriteLine(person["FirstName"]); // Ivan
Console.WriteLine(person["LastName"]); // Petrov
}
27
LINQ-to-JSON
JObjects can be queried with LINQ
var json = JObject.Parse(@"{'products': [
{'name': 'Fruits', 'products': ['apple', 'banana']},
{'name': 'Vegetables', 'products': ['cucumber']}]}");
Console.WriteLine(response.Content);
31
Using URL Segment Parameters
var client = new RestClient("https://api.github.com");
request.AddUrlSegment("user", "testnakov");
request.AddUrlSegment("repo", "test-nakov-repo");
request.AddUrlSegment("id", 1);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
32
Deserializing JSON Responses
var client = new RestClient("https://api.github.com");
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(new { title = "Title", body = "Body" });
Console.WriteLine(response.StatusCode);
35
API Testing for GitHub Issues
Testing RESTful Services
API Testing with NUnit + RestSharp
Creating API tests in C# with NUnit + RestSharp:
1. Create new NUnit Test Project in Visual Studio
2. Install the RestSharp package from NuGet
3. Write the test methods
37
Creating API Tests
Use MaxTimeout on the RestClient to establish a maximum
timeout that applies to all requests made by that client instance
38
Creating API Tests
Use Timeout on the RestRequest when you want to set a
timeout for individual requests
39
Problem: Testing the GitHub API
Using the GitHub official REST API
cerate the following requests and
test them:
List all issues from the repo
"testnakov/test-nakov-repo"
Create a new issue in the same repo
Edit created issue
You can check the results in the
project's issue tracker
40
Solution: Setup the Test Class
Setup the test class, create the REST client and configure HTTP
Basic Authentication
41
Solution: Get All Issues (HTTP GET)
42
Solution: Create New Issue (HTTP POST)
43
Solution: Edit Created Issue (HTTP PATCH)
44
Data-Driven API Tests
Using [TestCase] to Assign Data to Tests
Data-Driven Testing Recap
Data-driven testing == running the same test case with multiple
data (e. g. datasets in the C# code / Excel spreadsheet)
Each [TestCase(… data …)] creates a separate unit test
Data Set Testing Script
46
Zippopotam.us API
Zippopotam.us is free API
Provides location data by
country code + zip code
Example HTTP GET request:
https://api.zippopotam.us/ca/M5S
Use the "JSON Formatter"
plugin for Chrome to view the
JSON response
47
Data-Driven NUnit Tests with [ Main TestCase]
48
Data-Driven NUnit Tests with Classes
49
Summary
Understanding
… APIs: Interface for services
Serialization
… and Deserialization: Data to
format conversion
…
JSON: Data interchange and object mapping
How to use NUnit to structure the tests
and run them, and RestSharp to make
the HTTP requests to the API and verify
the responses
Data-Driven API Tests 50
Questions?
SoftUni Diamond Partners
52
Trainings @ Software University (SoftUni)
54