RestAPI Testing
RestAPI Testing
has a set of various functions which allows two applications to interact with each other .
It establishes a connection between client & server And acts as an intermediator between
client & server. Client side application sends a request through an API to server. Server does
some operations at the backend and provides the response to client.
For Example: in a restaurant , we place an order the waiter accepts our order & order is
processed in the “Kitchen”(backend). And waiter provides the order to us once ready. So
waiter here acts as an API.
API lets a developer make a specific “call” or “request” in order to send or receive
information. This communication is done using a programming language called “JSON.” It
can also be used to make a defined action such as updating or deleting data. There are four
basic request methods that can be made with API:
1. GET – Gathers information (Pulling all Coupon Codes).It is cacheable and can be
added from history and also can be bookmarked.
2. PUT – Updates pieces of data (Updating Product pricing)
3. POST – Creates (Creating a new Product Category) a new resource . and its not
cacheable.
4. DELETE – (Deleting a blog post)
JavaScript Object Notation is the programming language which is primarily used when data
is transmitted between a server and web application.
Rest API: REST is a software architectural style that defines the set of rules to be used for
creating web services. Web services which follow the REST architectural style are known
as RESTful web services. Interaction in REST based systems happen through Internet’s
Hypertext Transfer Protocol (HTTP)
There are six architectural constraints which makes any web service are listed below:
Uniform Interface: It is a key constraint that differentiate between a REST API and
Non-REST API. It suggests that there should be an uniform way of interacting with
a given server irrespective of device or type of application (website, mobile app).
Stateless: One client can send multiple requests to the server; however, each of
them must be independent, that is, every request must contain all the necessary
information so that the server can understand it and process it accordingly. In this
case, the server must not hold any information about the client state
Cacheable: Every response should include whether the response is cacheable or
not and for how much duration responses can be cached at the client side.
Client-Server: This constraint keeps the client and server loosely coupled. In this
case, the client does not need to know the implementation details in the server, and
the server is not worried about how the data is used by the client.
Layered System
Code on Demand
REST API is generally preferred over SOAP ,because REST uses less bandwidth, simple to
implement.
API testing is a software testing practice that tests the APIs directly — from their
functionality, reliability, performance, to security. As APIs or web services are the
building blocks of a software application. So it becomes important to validate the
core functionality/business logic of the application.
In GUI testing we send inputs via keyboard texts, button clicks, drop-down boxes, etc., on
the other hand in API testing we send requests (method calls) to the API and get output
(responses).
Functional testing. These API tests are designed to check that an API returns the
right response for a given request.
Load testing. This type of API test gauges how an API handles a large volume of
requests over a short period.
Runtime and error detection testing. These API tests are designed to evaluate the
actual running of the API and typically focus on monitoring, execution errors,
resource leaks, or error detection.
Security testing. These tests assess how an API responds to and resists cyberattacks.
Penetration Testing. Penetration tests involve users with limited API knowledge
trying to attack the API, which enables testers to assess the threat vector from an
outside perspective.
Fuzz Testing. This type of API test sends a large number of randomized requests to
see if your API responds with errors, processes any of these inputs incorrectly, or
crashes.
The term REST stands for REpresentational State Transfer. It is an architectural style that
defines a set of rules in order to create Web Services.
The API which follows the Design principles /rules of REST is REST API
In a client-server communication, REST suggests to create an object of the data requested
by the client and send the values of the object in response to the user.
It means when a RESTful API is called, the server will transfer a representation of the
requested resource’s state to the client system. This state representation can be in JSON,
XML, or HTML format.
RESTAssured:
It is open-source, hence any organization can use it for their project needs.
REST Assured is a Java library so it does not come as a GUI like other tools.
It is a framework to test REST services in Java.
It provides a Domain-Specific Language (DSL) to create an automation
script, uses any native language such as Java and tests the RESTful Web
API.
It supports XML and JSON format for the Request, Responses.
It acts as a headless client.
We can customize the request which we are going to send to the server
using this library.
Also, it can test a varied combination of complex business logic.
It is capable of fetching status code, responses, response body, headers
from the server for the sent request.
It enables the BDD style of writing test script i.e. in the format of GIVEN-
WHEN-THEN so that any business team member, especially from the non-
IT background, can also view it and understand the logic and test
coverage.
HTTP Request:
An HTTP request consists of the following:
1. Headers
2. URL
3. Method/Verb
4. Body
Headers
Headers represent the meta-data associated with HTTP requests or responses. It is the
additional information that is passed between client and server along with the request or
response. Headers are used for several purposes, such as authentication, caching, messaging
body information, handling cookies, etc. Headers will be key-value pairs or can be a key with
multiple values.
URL: The Request URL is the unique address used to make a request. URL consists of the
Base URL, Resource, Query, or Path Parameters.
3. Resource: A Resource represents the collection that can be accessed from the server.
Example: https://restful-booker.herokuapp.com/booking/{{id}}
4. Query Params: Query Parameters are optional parameters. It is used to sort/filter the
resource. For appending, the query parameter goes to the end of the URL by adding
‘?’ and implementing it as a key-value pair.One can also specify the multiple
parameters at the API endpoint and separate each parameter by the ‘&’ special
character.
Example: https://example.com/booking?category=science&chapeter=thermodynamics
Endpoints: It is basically an entry point of an API .
Body/Payload:
The Payload/Body contains the information that the user wants to send to the server. The
payload is used only with the requests that alter the existing resource or create new ones.
HTTP Response:
The HTTP Response consists of the status code, Headers and Response body
Static Imports:
We use them because of the class name. By importing Static, one can read the code
effectively and more understandable:
1. import Static io.restassured.*;
2. import Static org.hamcrest.*;
Example of Static imports: given().get().getStatusCode();
Authorization Vs Authentication:
Authorization is a process of allowing or disallowing some user to use some
APIs based on authentication.
Authentication is process of presenting user the credentials by the system,
then validating the credentials.
The status code is 401 which corresponds to unauthorized access and the
response message says Unauthorized.
Types of Authentication:
Authentication in simple words is basically verifying the identity of a particular user or client
application by presenting username/password or providing secret key or Authentication
tokens of the Web application etc. The different types of authorization are:
Session Cookies: These types of browser cookies delete once the session ends.
Permanent Cookies: These types of browser cookies remain on the system and
communicate with the server every time the website opens
Project Creation:
1. In pom.xml add the maven-compiler-plugin and maven-surefire-
plugin to run the testng.xml file
2. Add the rest-assured, hamcrest, TestNG, and JSON-simple
dependencies in the pom.xml
We know that REST Assured supports BDD format i.e given, when and then statements
given() — We provide all the input details here i.e. Base URI, Headers, Path
Parameter, Query Parameter, and Request Body/Payload.
when() — We specify the Resource, HTTP Request method like POST, GET, PUT,
PATCH, or DELETE.
then() — We validate the response i.e the response code, response time, response
message, response headers, response body, etc.
}
}
The method getStatusCode() is used to get the status code of the response.
This method returns an integer and then we can verify its value. TestNG
Assert is used to verify the Status Code.
When all the headers in a Response are returned, we can print each header by simply
iterating over each of them.
@Test
public void IteratingHeaders()
{ RestAssured.baseURI = "https://demoqa.com/BookStore/v1/Books";
RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest.get("");
// Get all the headers and then iterate over allHeaders to print each
header
Headers allHeaders = response.headers();
// Iterate over all the Headers
for(Header header : allHeaders) {
System.out.println("Key: " + header.getName() + " Value: " +
header.getValue());
}
}