API Testing with C#
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
{}
Serialization and Deserialization
Data Handling in RESTful APIs
1
Data Exchange
During RESTful API interactions, data is frequently exchanged
between a client and a server
The data must be in a format that both can understand
Serialization: Converts complex data structures or object
states into a flat format suitable for HTTP communication,
storage, or file-based persistence
Deserialization: Reconstructs the flat data back into usable
objects or data structures after it's received
Built-in JSON Support
.NET has built-in JSON support through the
System.Text.Json NuGet Package
It supports serializing objects and deserializing
(parsing) strings
Include the following namespaces into your project
using System.Text.Json;
using System.Text.Json.Serialization;
18
Serializing JSON
The System.Text.Json serializer can read and write JSON
class WeatherForecast
{
public DateTime Date { get; set; } = DateTime.Now;
public int TemperatureC { get; set; } = 30;
public string Summary { get; set; } = "Hot summer day";
}
static void Main()
{
WeatherForecast forecast = new WeatherForecast();
string weatherInfo = JsonSerializer.Serialize(forecast);
Console.WriteLine(weatherInfo);
}
19
Deserializing JSON
To deserialize from a file, we read the file into a string and then
use the Deserialize method
static void Main()
{
string jsonString = File.ReadAllText(file);
WeatherForecast forecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);
}
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);
Reading from file
var people = JObject.Parse(File.ReadAllText(@"c:\people.json"))
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']}]}");
var products = json["products"].Select(t =>
string.Format("{0} ({1})",
t["name"],
string.Join(", ", c["products"])
));
// Fruits (apple, banana)
// Vegetables (cucumber)
28
RestSharp
Simplifying REST API Calls in C#
RestSharp: REST API Client for C#
RestSharp is popular REST API client library for .NET
Very simple, quite powerful
Official site: https://restsharp.dev
Execute HTTP requests (sync & async)
Submit HTTP parameters, forms, query string, URL segment, etc.
Send / receive / serialize / parse JSON and XML payloads
Multiple authentication schemes: Basic, JWT, OAuth
Community of millions developers
30
Using RestSharp
Installing RestSharp through NuGet:
Executing simple HTTP GET request:
using RestSharp;
var client = new RestClient("https://api.github.com");
var request = new RestRequest("/users/softuni/repos", Method.Get);
var response = client.Execute(request);
Console.WriteLine(response.Content);
31
Using URL Segment Parameters
var client = new RestClient("https://api.github.com");
var request = new RestRequest(
"/repos/{user}/{repo}/issues/{id}", Method.Get);
request.AddUrlSegment("user", "testnakov");
request.AddUrlSegment("repo", "test-nakov-repo");
request.AddUrlSegment("id", 1);
var response = client.Execute(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
32
Deserializing JSON Responses
var client = new RestClient("https://api.github.com");
var request = new RestRequest(
"/users/softuni/repos", Method.Get);
var resp = client.Execute(request);
public class Repo { Reference the
public int id { get; set; } GitHub REST API
public string full_name { get; set; } documentation, which
public string html_url { get; set; } outlines the properties
} of a repository object
var repos = JsonSerializer.Deserialize<List<Repo>>(resp.Content);
33
GitHub Authentication
Reading from a public GitHub project is open to everyone
Modifying data in a GitHub project requires authentication
Get an API access token from your GitHub profile:
https://github.com/settings/tokens/new
Use HTTP basic authentication: username + token
Under "Select Scopes" Choose Repo
34
RestSharp: HTTP POST Request
Executing HTTP POST request with RestSharp:
var client = new RestClient(new RestClientOptions("https://api.github.com")
{
Authenticator = new HttpBasicAuthenticator("username", "api-token")
});
var request = new RestRequest
("/repos/testnakov/test-nakov-repo/issues", Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(new { title = "Title", body = "Body" });
var response = client.Execute(request);
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)
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg, about.softuni.bg
Software University Foundation
softuni.foundation
Software University @ Facebook
facebook.com/SoftwareUniversity
53
License
This course (slides, examples, demos, exercises, homework,
documents, videos and other assets) is copyrighted content
Unauthorized copy, reproduction or use is illegal
© SoftUni – https://about.softuni.bg/
© Software University – https://softuni.bg
54