SlideShare a Scribd company logo
Rest API Automation with
REST Assured
By Jaskeerat Singh Ubhi
1
Contents
S.No Topics Page
Number
1 Introduction 2
2. API Testing for Superior Outcomes 2
3. REST: API Testing With Efficiency 3
4. The Architectural Elements of REST 3
5. REST Constraints 4
5.1 Client – Server Architecture style 5
5.2 Stateless 5
5.3 Cache 5
5.4 Uniform Interface 6
5.5 Layered System 6
5.6 Code on Demand 6
6. What is REST Assured? 7
7. Performing API Testing With REST Assured 8
7.1 Getting Started: Configuration 8
7.2 First Test: Understanding Syntax 9
7.3 Validating Technical Response Data 11
7.4 Parameterizing Tests 11
7.5 Accessing Secured APIs 14
7.6 Passing Parameters Between Tests 15
7.7 Reusing Checks with ResponseSpecBuilder 16
8. Benefits of REST Assured 17
9. Other Salient Features of REST Assured 18
9.1 Technical Response Data Validation 18
9.2 Data-driven Testing 19
9.3 Support for Authentication Mechanisms 20
10. Conclusion 22
11. About the Author 22
12. About TO THE NEW 22
2
1. Introduction
With software trends such as IoT and mobile applications gaining greater prominence,
Application Programming Interfaces (APIs) have come to play a central role in their
development. Proper automated testing of APIs thus lies at the heart of developing
flawless products.
An API is a set of functions that are accessible to and can be executed by another
software system, essentially acting as an interface between different systems to facilitate
interaction and data exchange between them. API testing evaluates features such as
an app’s performance, security, functionality, and reliability. Unlike user interface (UI)
testing, it is more technical in nature and requires an additional understanding of the
internal workings of an application.
2. API Testing for Superior Outcomes
API testing is essential for fulfilling an emerging technological need. Many web
applications today are designed on a three-tier architectural model:
1) Presentation Tier – User Interface (UI)
2) Logic Tier – Also called the business tier, this is where business logic is written (API)
3) Data Tier – Used for storing and retrieving information from a Database (DB)
Ideally, these three layers should be independent. While UI can be tested with GUI testing
tools, the logic tier can be tested with API testing tools. API Testing refers to tests executed
on this tier, which comprises all business logic and is more complex than other tiers.
As agile development evolves, requirements frequently change and GUI testing is not
suitable for keeping pace with changes. Thus, API testing is all the more crucial to
testing application logic.
API testing is also preferred since it requires sending requests (method calls) to the API to
receive an output whereas in GUI testing we need to send inputs via keyboard texts,
drop-down boxes etc. Usually, APIs are REST or SOAP web services that feature JSON or
XML message payloads sent over JMS, HTTP, MQ, and HTTPS.
While the market offers many different tools for writing automated tests at the API level,
one of the most popular and efficient tools is REST Assured.
3
3. REST: API Testing With Efficiency
REpresentational State Transfer (REST) is an architectural style that employs simple HTTP
calls for inter-machine communication. It designs loosely coupled applications over HTTP
and is usually used in web services development. REST works by focusing on design rules
for creating stateless services and does not contain an additional messaging layer. The
resource can be accessed by a client using the unique URI and a representation of the
resource addressed to the URI is returned. With each new resource representation, the
client transfers state. The URL of the resource serves as the resource identifier while
accessing RESTful resources with GET, PUT, DELETE, POST and HEAD serving as the standard
HTTP operations to be performed on the resource.
REST doesn’t mandate any rules for its implementation at the lower level; instead, it
provides high level design guidelines and allows the user to figure out implementation by
themselves. RESTful API testing forms a crucial component of software quality assurance.
4. The Architectural Elements of REST
The architectural style of REST defines key conceptual elements for a RESTful service. Let’s
have a look at these elements:
Element Description
Resource In RESTful architecture, a resource is an asset that is available
on a server and can be requested by a client. For instance,
a weather API that returns weather information about a
particular city; the weather data is a resource hosted on the
server. A resource can either be temporal or static. While a
temporal resource changes with time (e.g. the weather), a
static resource stays constant over a long period (e.g. a
webpage containing static text).
4
Resource Identifier Every resource needs to be uniquely identifiable, which is
achieved through assigning a unique URL to it. For example,
a web service that returns the location from which Client is
making a call. Here, the resource would be the location while
the URL is a way to access it - the Resource Identifier.
However, a resource is not necessarily a static piece of
information. The URL would provide different results based on
locations, a dynamic component.
Representation A resource, which is the actual data, can be represented as
HTML, XML or simple text. That is called a representation. A
representation of a resource is its data plus metadata. The
metadata is a header explaining the format type of the
response body. For instance, a resource metadata may say
that the content in the response body is in JSON format. This
will help the client in interpreting the data.
Representation
Metadata
For the client to specify and process a resource with a
particular Representation (XML, HTML etc.), some extra data
(metadata) must be passed in the request.
5. REST Constraints
REST defines 6 architectural constraints which make any web service a true RESTful API.
5.1 Client – Server Architecture style
5
The first constraint in the REST architectural style is the Client-Server Architecture style. This
constraint sanctions the modeling of an application like a client–server. To relate to it, the
application should have the UI separate from the Data. The components handling the
Front end (UI) and the Back end (Database) should be distinct. This style of design is
important to allow the client and the server to evolve independently of each other. More
importantly, a server can serve multiple clients and clients can, in turn, use different
technologies. All that a client needs to know is resource URIs, a common practice to keep
things simple in web development today.
5.2 Stateless
The second constraint in REST architectural style debars the storage of the client context
by a server. Any request sent by the client is to be seen as completely independent of
previous ones. This constraint is important because it simplifies the server implementations
as there isn’t a need to store client references. The constraint also ensures that all the
requests made by clients should contain all the information required to service a request.
If a client application needs to be stateful for the end user, wherein they can perform a
host of authorized operations after logging in, each client request must contain all
information necessary to service it – such as authentication and authorization details.
However, no client context is stored on the server between requests and the responsibility
of managing the state of the application rests with the client.
5.3 Cache
This constraint ensures that the responses from the server contain relevant information to
indicate if they can be cached by the client. Caching data is important because it
improves client efficiency for cacheable responses and the client doesn’t need to make
requests to the server. This saves network bandwidth, improves performance and the
client’s processing power, resulting in a greater scope for scalability for the server as its
load reduces.
In REST, caching is applied on all possible resources, which must then necessarily declare
that they are cacheable. Caching can be implemented either on the server or the client
side. With well-managed caching, some client–server interactions can be eliminated,
thus improving scalability and performance.
6
5.4 Uniform Interface
A uniform interface is fundamental to the design of any REST service. A uniform interface
works by identifying resources, manipulating them, and processing self-descriptive
messages by taking Hypermedia as the engine of application state a.k.a. HATEOAS. Such
an interface simplifies and decouples the architecture, which enables each part to
evolve independently.
Testing with REST mandates deciding the API’s interface for resources that are exposed
to API consumers. A resource in the system should have just one logical URI and should
allow the fetching of related data. A resource should not be too large but must contain
all information in its representation. Whenever relevant, it should also contain links
(HATEOAS) pointing to relative URIs to fetch additional information. Additionally, across
the system, resource representations must follow guidelines such as naming conventions
or data format (xml or/and json). All resources must also be accessible through a
common approach such as HTTP GET and should be modified using a consistent
approach.
5.5 Layered System
A layered system is the fifth constraint in the REST architectural style. As the name
suggests, this constraint says that system implementation should be layered and each
layer should serve a certain functionality of the overall system. Apart from the layers that
directly interact with each other, all other layers should be independent of each other
and must not know of the existence of other layers.
Layered software isn’t limited to REST but serves at other platforms as well. It decreases
the overall complexity of the different components within the system. This enables
relatively smaller and cohesive pieces of functionality which makes it easier to implement
layers.
REST allows the use of a layered architecture where you can deploy the APIs on server A,
store data on server B, and authenticate requests on Server C. A client cannot tell
whether it is connected directly to the end server or to an intermediary.
5.6 Code on Demand
Code on demand is an optional constraint to be followed by RESTful architecture. This
enables the client to extend its functionality by downloading code directly from the
server. This code comes in the form of Applets or scripts. One example which shows how
7
code on demand can help clients extend their functionalities is JavaScript. On the
contrary, it raises security concerns as the server is able to send the code to the client.
For the most part, static representations of resources in form of XML or JSON are sent. But
you are also free to return executable code to support a part of your application. For
instance, it is permitted to serve a client request for an API to get a UI widget rendering
code.
It must be noted that the above constraints are closely related to the web. RESTful APIs
can be used to develop web services similar to web pages.
6. What is REST Assured?
An open source Java library, REST Assured offers a domain-specific language (DSL) for
writing powerful and maintainable automated tests for RESTful APIs. Developed by
JayWay Company, it acts as a powerful catalyzer for the automated testing of REST
Services. REST brings to the table several features including DSL- like syntax, XPath-
Validation, Specification Reuse, and easy file uploads, all of which smoothen the process
of API testing. The main features of REST Assured are:
· Specification reuse
· Response validation
· XPath verification
· Behavior-driven development syntax
Rest Assured has a gherkin type syntax which is shown below.
@Test
public void exampleRestTest() {
given()
.contentType(ContentType.JSON)
.pathParam("id", "AskJsd8Sd")
.when()
.get("/examplepath/{id}")
.then()
.statusCode(200)
.body("firstName", equalTo("Onur"))
.body("Surname", equalTo("Baskirt"));
}
8
Another method can be applied by obtaining JSON response as a string and then
sending it to the JsonPath class and then use its method to write more structured tests.
JsonPath is generally preferred for more structured tests.
@Test
public void exampleJsonPathTest() {
Response res = get("/service/example");
assertEquals(200, res.getStatusCode());
String json = res.asString();
JsonPath jp = new JsonPath(json);
assertEquals("onur@swtestacademy", jp.get("email"));
assertEquals("Onur", jp.get("firstName"));
assertEquals("Baskirt", jp.get("lastName"));
}
REST services are difficult to test and validate in Java as compared to other dynamic
languages such as Ruby and Groovy but REST Assured makes it simple to use these
languages in the Java domain. The framework sends a network request to an
application under test and verifies the response based on the expectations.
The library provides access to REST web services. Highly customizable HTTP Requests can
be created to send to the rightful server. This enables the testing of a wide variety of
request combinations and different combinations of core business logic as well. REST
Assured library also provides the ability to provide validation to the HTTP Responses
received from the server like verification of status code, status message, header and the
body of the response as well. All these features make REST Assured a very flexible library
that can be considered for API testing.
7. Performing API Testing With REST Assured
There are many different tools out there that can help in writing automated tests at the
API level. The following sections detail setting up and configuring REST Assured, writing
and running REST Assured tests, and applying its powerful features. These real-world code
examples can be copied, run, and reused directly in your test automation efforts.
7.1 Getting Started: Configuration
To get started with REST Assured, add it as a dependency on your project. If you're using
Maven, add the following entry to your pom.xml (change version number to reflect your
version):
9
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.0.2</version>
<scope>test</scope>
</dependency>
For Gradle:
testCompile 'io.rest-assured:rest-assured:3.0.2'
REST Assured is easy to use with existing unit testing frameworks such as JUnit and TestNG.
For the examples in this section, REST Assured has been used with TestNG.
Once you have the import of REST Assured set up, add the following static imports to your
test class:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
You’re now ready to create your first REST Assured test.
7.2 First Test: Understanding Syntax
This example is set by testing the Ergast Motor Racing Database API. This API provides
historical data related to Formula 1 races, drivers, circuits, and much more.
For an illustration of the way tests are written using REST Assured, here is a test that retrieves
the list of circuits for the 2017 Formula 1 season in JSON format and checks that there are
20 circuits in the list:
10
@Test
public void test_NumberOfCircuitsFor2017Season_ShouldBe20() {
given().
when().
get("http://ergast.com/api/f1/2017/circuits.json").
then().
assertThat().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(20));
}
It must be noted that the fluent API used by REST Assured supports the familiar
Given/When/Then syntax from behavior-driven development (BDD), resulting in a test
that is easy to read and takes care of everything (setup, execution, and verification) with
just a single line of code.
The hasSize()Hamcrest matcher counts the number of circuits, which is why Hamcrest
must be added as a static import. The Hamcrest library contains a collection of matchers
that allows to create verifications of all kinds while keeping them readable.
The verification part of the test is done to:
1) Capture the (JSON) response of the API call
2) Clarify for all elements called circuitId using the Groovy GPath expression
"MRData.CircuitTable.Circuits.circuitId"
3) Verify (using the aforementioned Hamcrest matcher) that the resulting collection of
circuitId elements has size 20
For a large number of different checks, Hamcrest matchers such as equalTo()for
equality, lessThan() and greaterThan() for comparison, hasItem() exist for checking
whether a collection contains a given element, and several more. Reference can be
taken from the Hamcrest library documentation for a full list of matchers.
To run the tests, use the test runner associated with the unit testing framework of either
JUnit or TestNG.
11
7.3 Validating Technical Response Data
REST Assured doesn’t only verify response body contents but also checks the accuracy
of technical response data such as the HTTP response status code, the response content
type, and other response headers. The example below is to check if:
· The response status code is equal to 200.
· The response content type (telling the receiver of the response how to interpret
the response body) equals "application/json."
· The value of the response header "Content-Length" equals "4567."
@Test
public void test_ResponseHeaderData_ShouldBeCorrect() {
given().
when().
get("http://ergast.com/api/f1/2017/circuits.json").
then().
assertThat().
statusCode(200).
and().
contentType(ContentType.JSON).
and().
header("Content-Length",equalTo("4567"));
}
This example also depicts how checks can be easily concatenated in a readable
manner using the and() method, which eventually makes the code more readable.
7.4 Parameterizing Tests
Often, repeating the same test with various sets of (input and output) parameters is
required, a concept known as data-driven testing. In this case, instead of writing a new
test for each test data record, a parameterized test is created and fed with as many test
data records as the desired test coverage demands.
12
RESTful APIs support two different types of parameters:
· Query parameters are appended at the end of a RESTful API endpoint. It can be
identified by the question mark in front of them. For example, in the endpoint
http://md5.jsontest.com/?text=test, "text" is a query parameter (with value "test").
· Path parameters are part of the RESTful API endpoint. For example, in the endpoint
used earlier: http://ergast.com/api/f1/2017/circuits.json, "2017" is a path parameter
value. If replaced with "2016" the previous test would fail, since there were 21 Formula 1
races in 2016, not 20.
REST Assured can work with both types of parameters. First, it is mentioned how the query
parameter from the above example can be used and specified.
@Test
public voidtest_Md5CheckSumForTest_ShouldBe098f6bcd4621d373cade4e832627b4f6()
{
String originalText = "test";
String expectedMd5CheckSum = "098f6bcd4621d373cade4e832627b4f6";
given().
param("text",originalText).
when().
get("http://md5.jsontest.com").
then().
assertThat().
body("md5",equalTo(expectedMd5CheckSum));
}
Using query parameters in REST Assured is as simple as specifying their name and value
using the param(). Path parameters are specified similarly:
13
@Test
public void test_NumberOfCircuits_ShouldBe20_Parameterized() {
String season = "2017";
int numberOfRaces = 20;
given().
pathParam("raceSeason",season).
when().
get("http://ergast.com/api/f1/{raceSeason}/circuits.json").
then().
assertThat().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(numberOfRaces));
}
In the given case, the path parameters are defined using the pathParam() method rather
than param(). In addition, defining the part of the endpoint path that represents the path
variable is required, which is done using the curly bracket notation seen in the example
above. This way, more than one parameter can be easily created and both the path
and query parameters can be combined in a single call if the API supports or requires
this.
After creating this parameterized test, the next task would be to make it data-driven by
using an external test data set. For ease, it is recommended to get it done with TestNG,
even though Junit supports parameterization as well. TestNG is easier as it is only needed
to create a DataProvider object containing the required test data as in this case it is the
set of records containing years and number of Formula 1 races in each year.
@DataProvider(name="seasonsAndNumberOfRaces")
public Object[][] createTestDataRecords() {
return new Object[][] {
{"2017",20},
{"2016",21},
{"1966",9}
};
}
14
The next step would be to pass the test data object to the parameterized test through
test method parameters:
@Test(dataProvider="seasonsAndNumberOfRaces")
public void test_NumberOfCircuits_ShouldBe_DataDriven(String season, int numberOfRaces)
{
given().
pathParam("raceSeason",season).
when().
get("http://ergast.com/api/f1/{raceSeason}/circuits.json").
then().
assertThat().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(numberOfRaces));
}
When dealing with a test data object, test cases can be added, removed or updated
by creating, deleting or modifying the appropriate test data record. In a case where the
test itself needs to be updated such as when the endpoint or the response body structure
changes it is needed to update the test and all test cases will follow the updated
procedure.
7.5 Accessing Secured APIs
The security of APIs is often ensured with some or the other sort of authentication
mechanism. REST Assured supports basic, digest, form, and OAuth authentication. The
following example demonstrates how call a RESTful API that has been secured using basic
authentication can be done (i.e., the consumer of this API needs to provide a valid
username and password combination every time they call the API):
@Test
public void test_APIWithBasicAuthentication_ShouldBeGivenAccess() {
given().
auth().
preemptive().
basic("username", "password").
when().
get("http://path.to/basic/secured/api").
then().
assertThat().
statusCode(200);
}
15
Accessing an OAuth2-secured API pretty straightforward, given that you have a valid
authentication token:
@Test
public void test_APIWithOAuth2Authentication_ShouldBeGivenAccess() {
given().
auth().
oauth2(YOUR_AUTHENTICATION_TOKEN_GOES_HERE).
when().
get("http://path.to/oath2/secured/api").
then().
assertThat().
statusCode(200);
}
7.6 Passing Parameters Between Tests
When testing RESTful APIs, it is often required to create more complex test scenarios when it is
needed to capture a value from the resource of one API call and reuse it in a subsequent call.
This is supported by REST Assured using the extract() method. The example here shows a test
scenario that extracts the ID for the first circuit of the 2017
Formula 1 season and uses it to retrieve and verify additional information on that circuit
(in this case, the circuit is located in Australia):
16
@Test
public void
test_ScenarioRetrieveFirstCircuitFor2017SeasonAndGetCountry_ShouldBeAustralia() {
// First, retrieve the circuit ID for the first circuit of the 2017 season
String circuitId = given().
when().
get("http://ergast.com/api/f1/2017/circuits.json").
then().
extract().
path("MRData.CircuitTable.Circuits.circuitId[0]");
// Then, retrieve the information known for that circuit and verify it is located in Australia
given().
pathParam("circuitId",circuitId).
when().
get("http://ergast.com/api/f1/circuits/{circuitId}.json").
then().
assertThat().
body("MRData.CircuitTable.Circuits.Location[0].country",equalTo("Australia"));
}
7.7 Reusing Checks with ResponseSpecBuilder
The reusability and maintainability of RESTful API tests can also be improved by reusing
checks. For example, to check if all the API responses have a status code equal to 200
and a content type equal to "application/json,", it can be tiresome to specify this for each
and every test.
Another case considered, in addition, if for some reason the default status code and
content type returned changes, it’d rather be affluent to only have to update this in one
place, instead of throughout the test suite. Using the ResponseSpecBuilder mechanism,
REST Assured supports reuse of specific verifications.
The below example shows how a reusable Response Specification that checks
aforementioned status code can be created and used in a test:
17
ResponseSpecification checkStatusCodeAndContentType =
new ResponseSpecBuilder().
expectStatusCode(200).
expectContentType(ContentType.JSON).
build();
@Test
public void test_NumberOfCircuits_ShouldBe20_UsingResponseSpec() {
given().
when().
get("http://ergast.com/api/f1/2017/circuits.json").
then().
assertThat().
spec(checkStatusCodeAndContentType).
and().
body("MRData.CircuitTable.Circuits.circuitId",hasSize(20));
}
The checks that are specific to that test in addition to using the Response Specification
can be created.
8. Benefits of REST Assured
It is no doubt that REST Assured is a powerful library for API testing. Let’s see how:
· It removes the need for writing a lot of boilerplate code which is required to set up
an HTTP connection, send a request and receive and parse a response.
· It supports a Given/When/Then test notation, which instantly makes tests human
readable.
· Since REST Assured is a Java library, integrating it into a continuous integration /
continuous delivery setup is a breeze, especially when combined with a Java testing
framework such as JUnit or TestNG.
18
For further illustration of the benefits of REST Assured, a simple REST Assured test is
mentioned below. This test invokes a GET call to an API that, based on a zip code and a
country code, provides some data on the location corresponding to that zip code. So,
an example of the behavior of this API would look like this:
· Given a specific country (in this case the India) and zip-code (in this case 110001)
· When we perform a GET call to the RESTful API
· Then the response returned indicates that the 110001 zip-code corresponds to New
Delhi.
9. Other Salient Features of REST Assured
REST Assured offers a number of useful features for writing RESTful API tests.
9.1 Technical Response Data Validation
When checking if an API works as intended, it is not enough to just check response
contents. For the application receiving the response, it is of importance that the response
is technically sound; e.g., checking if the response has the right status code, header
values, and formatting. All of these can be easily checked using REST Assured. For
instance, to check if the response for a previously executed API call has a status code of
200 (indicating all is OK) and that the response header indicates that the body is to be
interpreted as JSON, the following can be done:
@Test
public void checkHeaderData() {
given().
pathParam("country","us").
pathParam("zipcode","90210").
when().
get("http://api.zippopotam.us/{country}/{zipcode}").
then().
assertThat().
statusCode(200).
and().
contentType(ContentType.JSON);
}
19
It is clear that with REST Assured, verifying technical response data is as straightforward as
checking response body contents.
9.2 Data-driven Testing
Another REST feature that makes API testing more powerful is its ability to create data-
driven tests. For instance, if you want to check that zip code 12345 is associated with the
city of Schenectady, New York. But instead of simply copying the entire test and
replacing relevant parts, you would like to feed a single test with two different data
records (this is called data-driven testing) to reduce potential maintenance efforts while
making it easy to add even more tests.
To do this, you will first need to create a test data set. This example uses the DataProvider
object offered by TestNG:
@DataProvider(name = "zipcodes")
public String[][] createZipCodeTestData() {
return new String[][] {
{"us","90210","Beverly Hills"},
{"us","12345","Schenectady"}
};
}
Next, you will create a data-driven REST Assured test associated with this test data set:
@Test(dataProvider = "zipcodes")
public void aZipCodeTest(String country, String zipcode, String city) {
given().
pathParam("country",country).
pathParam("zipcode",zipcode).
when().
get("http://api.zippopotam.us/{country}/{zipcode}").
then().
assertThat().
body("places.'place name'[0]",equalTo(city));
}
20
When you run this test, it'll be executed twice for each record in the test data set. It can
be seen that creating data-driven tests in REST Assured is a straightforward step once you
have tests in place for a single test data record.
9.3 Support for Authentication Mechanisms
A lot of RESTful APIs require consumer authentication before interaction. REST Assured
supports a number of commonly used API authentication mechanisms, including Basic
(username and a password in the header of every call) and OAuth 2.0 authentication.
Here’s how you can call a Basic authentication secured API with REST Assured.
@Test
public void checkBasicAuthentication() {
given().
auth().
preemptive().
basic("username","password").
when().
get("http://mysecureapi.com/basicauth").
then().
assertThat().
body("authentication_result",equalTo("Success"));
}
There are several other useful features that REST Assured offers for creating powerful tests:
· REST Assured has the ability to (de-)serialize Plain Old Java Objects (POJOs). This
enables to serialize the properties and values associated with a Java object instance
directly into a JSON or an XML document, which can further be sent to a RESTful API using
the POST method. It works the other way around as well i.e. a JSON or an XML response
returned by an API can be deserialized into a POJO instance by REST Assured as well.
· Another interesting feature of REST Assured is Logging requests and responses. This
can be especially useful when it is needed to inspect API responses to create the
appropriate checks, or to make sure that the request being sent to an API is correct.
Everything (parameters, headers, and body), only headers, only parameters, and much
more can be logged.
· REST Assured comes with a Spring Mock MVC module, which enables writing tests
for Spring controllers using the REST Assured syntax.
21
10. Conclusion
Today, almost all web applications use web services to communicate or interact with
each other. Most modern-day web services are built on Representational state transfer
(REST) architecture. REST’s popularity will only increase with time owing to its ease of use
compared to other technologies.
It is thus becoming imperative for software QA engineers, automation engineers, and
software developers to understand the importance of web services testing and more
importantly automating the process. Automating API tests is crucial for most projects due
to the fact that API tests are far more stable, reliable, and fast. API automation with REST
Assured is certainly the way forward in API testing.
11. About the Author
Jaskeerat - Sr. Testing/QA Engineer
TO THE NEW
Jaskeerat Singh Ubhi is a ISTQB and Oracle Certified testing professional. He likes to invest
time in learning automation testing tools and technologies. Jaskeerat is also interested
and passionate about automating web and mobile applications
12. About TO THE NEW
TO THE NEW is a premium digital technology company that provides end-to-end product
development services. TO THE NEW leverages the power of experience design, cutting-
edge engineering and cloud to build disruptive web and mobile products and enable
digital transformation for businesses.
TO THE NEW practices Agile methodologies to develop innovative products with a faster
time to market. With a team of 750+ passionate technologists, TO THE NEW constantly
challenges the status quo to empower Fortune 500 companies as well as startups across
the globe.

More Related Content

What's hot

API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)
Peter Thomas
 
API Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj RollisonAPI Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj Rollison
TEST Huddle
 
Belajar Postman test runner
Belajar Postman test runnerBelajar Postman test runner
Belajar Postman test runner
Fachrul Choliluddin
 
Test your microservices with REST-Assured
Test your microservices with REST-AssuredTest your microservices with REST-Assured
Test your microservices with REST-Assured
Michel Schudel
 
Api testing
Api testingApi testing
Api testing
Keshav Kashyap
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
Anirudh Raja
 
API Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+CucumberAPI Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+Cucumber
Knoldus Inc.
 
B4USolution_API-Testing
B4USolution_API-TestingB4USolution_API-Testing
B4USolution_API-Testing
b4usolution .
 
Api Testing
Api TestingApi Testing
Api Testing
Vishwanath KC
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
Andrey Oleynik
 
Api testing
Api testingApi testing
Api testing
HamzaMajid13
 
Postman.ppt
Postman.pptPostman.ppt
Postman.ppt
ParrotBAD
 
An introduction to api testing | David Tzemach
An introduction to api testing | David TzemachAn introduction to api testing | David Tzemach
An introduction to api testing | David Tzemach
David Tzemach
 
Postman & API Testing by Amber Race
Postman & API Testing by Amber RacePostman & API Testing by Amber Race
Postman & API Testing by Amber Race
Postman
 
API Testing With Katalon Studio
API Testing With Katalon StudioAPI Testing With Katalon Studio
API Testing With Katalon Studio
Knoldus Inc.
 
Test Design and Automation for REST API
Test Design and Automation for REST APITest Design and Automation for REST API
Test Design and Automation for REST API
Ivan Katunou
 
API TESTING
API TESTINGAPI TESTING
API TESTING
Sijan Bhandari
 
4 Major Advantages of API Testing
4 Major Advantages of API Testing4 Major Advantages of API Testing
4 Major Advantages of API Testing
QASource
 
Rest API Testing
Rest API TestingRest API Testing
Rest API Testing
upadhyay_25
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingKarate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
 

What's hot (20)

API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)API Test Automation Using Karate (Anil Kumar Moka)
API Test Automation Using Karate (Anil Kumar Moka)
 
API Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj RollisonAPI Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj Rollison
 
Belajar Postman test runner
Belajar Postman test runnerBelajar Postman test runner
Belajar Postman test runner
 
Test your microservices with REST-Assured
Test your microservices with REST-AssuredTest your microservices with REST-Assured
Test your microservices with REST-Assured
 
Api testing
Api testingApi testing
Api testing
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
API Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+CucumberAPI Automation Testing Using RestAssured+Cucumber
API Automation Testing Using RestAssured+Cucumber
 
B4USolution_API-Testing
B4USolution_API-TestingB4USolution_API-Testing
B4USolution_API-Testing
 
Api Testing
Api TestingApi Testing
Api Testing
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
Api testing
Api testingApi testing
Api testing
 
Postman.ppt
Postman.pptPostman.ppt
Postman.ppt
 
An introduction to api testing | David Tzemach
An introduction to api testing | David TzemachAn introduction to api testing | David Tzemach
An introduction to api testing | David Tzemach
 
Postman & API Testing by Amber Race
Postman & API Testing by Amber RacePostman & API Testing by Amber Race
Postman & API Testing by Amber Race
 
API Testing With Katalon Studio
API Testing With Katalon StudioAPI Testing With Katalon Studio
API Testing With Katalon Studio
 
Test Design and Automation for REST API
Test Design and Automation for REST APITest Design and Automation for REST API
Test Design and Automation for REST API
 
API TESTING
API TESTINGAPI TESTING
API TESTING
 
4 Major Advantages of API Testing
4 Major Advantages of API Testing4 Major Advantages of API Testing
4 Major Advantages of API Testing
 
Rest API Testing
Rest API TestingRest API Testing
Rest API Testing
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testingKarate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
 

Similar to Rest API Automation with REST Assured

Rest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbook
Katy Slemon
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
IRJET Journal
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
NamanVerma88
 
A Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework SurveyA Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework Survey
IRJET Journal
 
REST & RESTful APIs: The State of Confusion
REST & RESTful APIs: The State of ConfusionREST & RESTful APIs: The State of Confusion
REST & RESTful APIs: The State of Confusion
Glenn Antoine
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
Aparna Sharma
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
Aparna Sharma
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?
Aparna Sharma
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
Halil Burak Cetinkaya
 
REST - Representational State Transfer
REST - Representational State TransferREST - Representational State Transfer
REST - Representational State Transfer
Peter R. Egli
 
Rest web service
Rest web serviceRest web service
Rest web service
Hamid Ghorbani
 
Rest surekha
Rest surekhaRest surekha
Rest surekha
Surekha Achanta
 
API Testing Basics.pptx
API Testing Basics.pptxAPI Testing Basics.pptx
API Testing Basics.pptx
VikasGupta92111
 
Best Practices in Api Design
Best Practices in Api DesignBest Practices in Api Design
Best Practices in Api Design
Muhammad Aamir ...
 
REST Introduction.ppt
REST Introduction.pptREST Introduction.ppt
REST Introduction.ppt
KGSCSEPSGCT
 
Code-Camp-Rest-Principles
Code-Camp-Rest-PrinciplesCode-Camp-Rest-Principles
Code-Camp-Rest-Principles
Knoldus Inc.
 
Enterprise Software Architecture
Enterprise Software ArchitectureEnterprise Software Architecture
Enterprise Software Architecturerahmed_sct
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
Sudheer Satyanarayana
 
Restful api
Restful apiRestful api
Restful api
Anurag Srivastava
 

Similar to Rest API Automation with REST Assured (20)

Rest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbook
 
IRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce SiteIRJET- Rest API for E-Commerce Site
IRJET- Rest API for E-Commerce Site
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
A Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework SurveyA Deep Dive into REST API Framework Survey
A Deep Dive into REST API Framework Survey
 
REST & RESTful APIs: The State of Confusion
REST & RESTful APIs: The State of ConfusionREST & RESTful APIs: The State of Confusion
REST & RESTful APIs: The State of Confusion
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
ReSTful API Final
ReSTful API FinalReSTful API Final
ReSTful API Final
 
Modern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdfModern REST API design principles and rules.pdf
Modern REST API design principles and rules.pdf
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
REST - Representational State Transfer
REST - Representational State TransferREST - Representational State Transfer
REST - Representational State Transfer
 
Rest web service
Rest web serviceRest web service
Rest web service
 
Rest surekha
Rest surekhaRest surekha
Rest surekha
 
API Testing Basics.pptx
API Testing Basics.pptxAPI Testing Basics.pptx
API Testing Basics.pptx
 
Best Practices in Api Design
Best Practices in Api DesignBest Practices in Api Design
Best Practices in Api Design
 
REST Introduction.ppt
REST Introduction.pptREST Introduction.ppt
REST Introduction.ppt
 
Code-Camp-Rest-Principles
Code-Camp-Rest-PrinciplesCode-Camp-Rest-Principles
Code-Camp-Rest-Principles
 
Enterprise Software Architecture
Enterprise Software ArchitectureEnterprise Software Architecture
Enterprise Software Architecture
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
 
Restful api
Restful apiRestful api
Restful api
 

Recently uploaded

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 

Rest API Automation with REST Assured

  • 1. Rest API Automation with REST Assured By Jaskeerat Singh Ubhi
  • 2. 1 Contents S.No Topics Page Number 1 Introduction 2 2. API Testing for Superior Outcomes 2 3. REST: API Testing With Efficiency 3 4. The Architectural Elements of REST 3 5. REST Constraints 4 5.1 Client – Server Architecture style 5 5.2 Stateless 5 5.3 Cache 5 5.4 Uniform Interface 6 5.5 Layered System 6 5.6 Code on Demand 6 6. What is REST Assured? 7 7. Performing API Testing With REST Assured 8 7.1 Getting Started: Configuration 8 7.2 First Test: Understanding Syntax 9 7.3 Validating Technical Response Data 11 7.4 Parameterizing Tests 11 7.5 Accessing Secured APIs 14 7.6 Passing Parameters Between Tests 15 7.7 Reusing Checks with ResponseSpecBuilder 16 8. Benefits of REST Assured 17 9. Other Salient Features of REST Assured 18 9.1 Technical Response Data Validation 18 9.2 Data-driven Testing 19 9.3 Support for Authentication Mechanisms 20 10. Conclusion 22 11. About the Author 22 12. About TO THE NEW 22
  • 3. 2 1. Introduction With software trends such as IoT and mobile applications gaining greater prominence, Application Programming Interfaces (APIs) have come to play a central role in their development. Proper automated testing of APIs thus lies at the heart of developing flawless products. An API is a set of functions that are accessible to and can be executed by another software system, essentially acting as an interface between different systems to facilitate interaction and data exchange between them. API testing evaluates features such as an app’s performance, security, functionality, and reliability. Unlike user interface (UI) testing, it is more technical in nature and requires an additional understanding of the internal workings of an application. 2. API Testing for Superior Outcomes API testing is essential for fulfilling an emerging technological need. Many web applications today are designed on a three-tier architectural model: 1) Presentation Tier – User Interface (UI) 2) Logic Tier – Also called the business tier, this is where business logic is written (API) 3) Data Tier – Used for storing and retrieving information from a Database (DB) Ideally, these three layers should be independent. While UI can be tested with GUI testing tools, the logic tier can be tested with API testing tools. API Testing refers to tests executed on this tier, which comprises all business logic and is more complex than other tiers. As agile development evolves, requirements frequently change and GUI testing is not suitable for keeping pace with changes. Thus, API testing is all the more crucial to testing application logic. API testing is also preferred since it requires sending requests (method calls) to the API to receive an output whereas in GUI testing we need to send inputs via keyboard texts, drop-down boxes etc. Usually, APIs are REST or SOAP web services that feature JSON or XML message payloads sent over JMS, HTTP, MQ, and HTTPS. While the market offers many different tools for writing automated tests at the API level, one of the most popular and efficient tools is REST Assured.
  • 4. 3 3. REST: API Testing With Efficiency REpresentational State Transfer (REST) is an architectural style that employs simple HTTP calls for inter-machine communication. It designs loosely coupled applications over HTTP and is usually used in web services development. REST works by focusing on design rules for creating stateless services and does not contain an additional messaging layer. The resource can be accessed by a client using the unique URI and a representation of the resource addressed to the URI is returned. With each new resource representation, the client transfers state. The URL of the resource serves as the resource identifier while accessing RESTful resources with GET, PUT, DELETE, POST and HEAD serving as the standard HTTP operations to be performed on the resource. REST doesn’t mandate any rules for its implementation at the lower level; instead, it provides high level design guidelines and allows the user to figure out implementation by themselves. RESTful API testing forms a crucial component of software quality assurance. 4. The Architectural Elements of REST The architectural style of REST defines key conceptual elements for a RESTful service. Let’s have a look at these elements: Element Description Resource In RESTful architecture, a resource is an asset that is available on a server and can be requested by a client. For instance, a weather API that returns weather information about a particular city; the weather data is a resource hosted on the server. A resource can either be temporal or static. While a temporal resource changes with time (e.g. the weather), a static resource stays constant over a long period (e.g. a webpage containing static text).
  • 5. 4 Resource Identifier Every resource needs to be uniquely identifiable, which is achieved through assigning a unique URL to it. For example, a web service that returns the location from which Client is making a call. Here, the resource would be the location while the URL is a way to access it - the Resource Identifier. However, a resource is not necessarily a static piece of information. The URL would provide different results based on locations, a dynamic component. Representation A resource, which is the actual data, can be represented as HTML, XML or simple text. That is called a representation. A representation of a resource is its data plus metadata. The metadata is a header explaining the format type of the response body. For instance, a resource metadata may say that the content in the response body is in JSON format. This will help the client in interpreting the data. Representation Metadata For the client to specify and process a resource with a particular Representation (XML, HTML etc.), some extra data (metadata) must be passed in the request. 5. REST Constraints REST defines 6 architectural constraints which make any web service a true RESTful API. 5.1 Client – Server Architecture style
  • 6. 5 The first constraint in the REST architectural style is the Client-Server Architecture style. This constraint sanctions the modeling of an application like a client–server. To relate to it, the application should have the UI separate from the Data. The components handling the Front end (UI) and the Back end (Database) should be distinct. This style of design is important to allow the client and the server to evolve independently of each other. More importantly, a server can serve multiple clients and clients can, in turn, use different technologies. All that a client needs to know is resource URIs, a common practice to keep things simple in web development today. 5.2 Stateless The second constraint in REST architectural style debars the storage of the client context by a server. Any request sent by the client is to be seen as completely independent of previous ones. This constraint is important because it simplifies the server implementations as there isn’t a need to store client references. The constraint also ensures that all the requests made by clients should contain all the information required to service a request. If a client application needs to be stateful for the end user, wherein they can perform a host of authorized operations after logging in, each client request must contain all information necessary to service it – such as authentication and authorization details. However, no client context is stored on the server between requests and the responsibility of managing the state of the application rests with the client. 5.3 Cache This constraint ensures that the responses from the server contain relevant information to indicate if they can be cached by the client. Caching data is important because it improves client efficiency for cacheable responses and the client doesn’t need to make requests to the server. This saves network bandwidth, improves performance and the client’s processing power, resulting in a greater scope for scalability for the server as its load reduces. In REST, caching is applied on all possible resources, which must then necessarily declare that they are cacheable. Caching can be implemented either on the server or the client side. With well-managed caching, some client–server interactions can be eliminated, thus improving scalability and performance.
  • 7. 6 5.4 Uniform Interface A uniform interface is fundamental to the design of any REST service. A uniform interface works by identifying resources, manipulating them, and processing self-descriptive messages by taking Hypermedia as the engine of application state a.k.a. HATEOAS. Such an interface simplifies and decouples the architecture, which enables each part to evolve independently. Testing with REST mandates deciding the API’s interface for resources that are exposed to API consumers. A resource in the system should have just one logical URI and should allow the fetching of related data. A resource should not be too large but must contain all information in its representation. Whenever relevant, it should also contain links (HATEOAS) pointing to relative URIs to fetch additional information. Additionally, across the system, resource representations must follow guidelines such as naming conventions or data format (xml or/and json). All resources must also be accessible through a common approach such as HTTP GET and should be modified using a consistent approach. 5.5 Layered System A layered system is the fifth constraint in the REST architectural style. As the name suggests, this constraint says that system implementation should be layered and each layer should serve a certain functionality of the overall system. Apart from the layers that directly interact with each other, all other layers should be independent of each other and must not know of the existence of other layers. Layered software isn’t limited to REST but serves at other platforms as well. It decreases the overall complexity of the different components within the system. This enables relatively smaller and cohesive pieces of functionality which makes it easier to implement layers. REST allows the use of a layered architecture where you can deploy the APIs on server A, store data on server B, and authenticate requests on Server C. A client cannot tell whether it is connected directly to the end server or to an intermediary. 5.6 Code on Demand Code on demand is an optional constraint to be followed by RESTful architecture. This enables the client to extend its functionality by downloading code directly from the server. This code comes in the form of Applets or scripts. One example which shows how
  • 8. 7 code on demand can help clients extend their functionalities is JavaScript. On the contrary, it raises security concerns as the server is able to send the code to the client. For the most part, static representations of resources in form of XML or JSON are sent. But you are also free to return executable code to support a part of your application. For instance, it is permitted to serve a client request for an API to get a UI widget rendering code. It must be noted that the above constraints are closely related to the web. RESTful APIs can be used to develop web services similar to web pages. 6. What is REST Assured? An open source Java library, REST Assured offers a domain-specific language (DSL) for writing powerful and maintainable automated tests for RESTful APIs. Developed by JayWay Company, it acts as a powerful catalyzer for the automated testing of REST Services. REST brings to the table several features including DSL- like syntax, XPath- Validation, Specification Reuse, and easy file uploads, all of which smoothen the process of API testing. The main features of REST Assured are: · Specification reuse · Response validation · XPath verification · Behavior-driven development syntax Rest Assured has a gherkin type syntax which is shown below. @Test public void exampleRestTest() { given() .contentType(ContentType.JSON) .pathParam("id", "AskJsd8Sd") .when() .get("/examplepath/{id}") .then() .statusCode(200) .body("firstName", equalTo("Onur")) .body("Surname", equalTo("Baskirt")); }
  • 9. 8 Another method can be applied by obtaining JSON response as a string and then sending it to the JsonPath class and then use its method to write more structured tests. JsonPath is generally preferred for more structured tests. @Test public void exampleJsonPathTest() { Response res = get("/service/example"); assertEquals(200, res.getStatusCode()); String json = res.asString(); JsonPath jp = new JsonPath(json); assertEquals("onur@swtestacademy", jp.get("email")); assertEquals("Onur", jp.get("firstName")); assertEquals("Baskirt", jp.get("lastName")); } REST services are difficult to test and validate in Java as compared to other dynamic languages such as Ruby and Groovy but REST Assured makes it simple to use these languages in the Java domain. The framework sends a network request to an application under test and verifies the response based on the expectations. The library provides access to REST web services. Highly customizable HTTP Requests can be created to send to the rightful server. This enables the testing of a wide variety of request combinations and different combinations of core business logic as well. REST Assured library also provides the ability to provide validation to the HTTP Responses received from the server like verification of status code, status message, header and the body of the response as well. All these features make REST Assured a very flexible library that can be considered for API testing. 7. Performing API Testing With REST Assured There are many different tools out there that can help in writing automated tests at the API level. The following sections detail setting up and configuring REST Assured, writing and running REST Assured tests, and applying its powerful features. These real-world code examples can be copied, run, and reused directly in your test automation efforts. 7.1 Getting Started: Configuration To get started with REST Assured, add it as a dependency on your project. If you're using Maven, add the following entry to your pom.xml (change version number to reflect your version):
  • 10. 9 <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.2</version> <scope>test</scope> </dependency> For Gradle: testCompile 'io.rest-assured:rest-assured:3.0.2' REST Assured is easy to use with existing unit testing frameworks such as JUnit and TestNG. For the examples in this section, REST Assured has been used with TestNG. Once you have the import of REST Assured set up, add the following static imports to your test class: import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; You’re now ready to create your first REST Assured test. 7.2 First Test: Understanding Syntax This example is set by testing the Ergast Motor Racing Database API. This API provides historical data related to Formula 1 races, drivers, circuits, and much more. For an illustration of the way tests are written using REST Assured, here is a test that retrieves the list of circuits for the 2017 Formula 1 season in JSON format and checks that there are 20 circuits in the list:
  • 11. 10 @Test public void test_NumberOfCircuitsFor2017Season_ShouldBe20() { given(). when(). get("http://ergast.com/api/f1/2017/circuits.json"). then(). assertThat(). body("MRData.CircuitTable.Circuits.circuitId",hasSize(20)); } It must be noted that the fluent API used by REST Assured supports the familiar Given/When/Then syntax from behavior-driven development (BDD), resulting in a test that is easy to read and takes care of everything (setup, execution, and verification) with just a single line of code. The hasSize()Hamcrest matcher counts the number of circuits, which is why Hamcrest must be added as a static import. The Hamcrest library contains a collection of matchers that allows to create verifications of all kinds while keeping them readable. The verification part of the test is done to: 1) Capture the (JSON) response of the API call 2) Clarify for all elements called circuitId using the Groovy GPath expression "MRData.CircuitTable.Circuits.circuitId" 3) Verify (using the aforementioned Hamcrest matcher) that the resulting collection of circuitId elements has size 20 For a large number of different checks, Hamcrest matchers such as equalTo()for equality, lessThan() and greaterThan() for comparison, hasItem() exist for checking whether a collection contains a given element, and several more. Reference can be taken from the Hamcrest library documentation for a full list of matchers. To run the tests, use the test runner associated with the unit testing framework of either JUnit or TestNG.
  • 12. 11 7.3 Validating Technical Response Data REST Assured doesn’t only verify response body contents but also checks the accuracy of technical response data such as the HTTP response status code, the response content type, and other response headers. The example below is to check if: · The response status code is equal to 200. · The response content type (telling the receiver of the response how to interpret the response body) equals "application/json." · The value of the response header "Content-Length" equals "4567." @Test public void test_ResponseHeaderData_ShouldBeCorrect() { given(). when(). get("http://ergast.com/api/f1/2017/circuits.json"). then(). assertThat(). statusCode(200). and(). contentType(ContentType.JSON). and(). header("Content-Length",equalTo("4567")); } This example also depicts how checks can be easily concatenated in a readable manner using the and() method, which eventually makes the code more readable. 7.4 Parameterizing Tests Often, repeating the same test with various sets of (input and output) parameters is required, a concept known as data-driven testing. In this case, instead of writing a new test for each test data record, a parameterized test is created and fed with as many test data records as the desired test coverage demands.
  • 13. 12 RESTful APIs support two different types of parameters: · Query parameters are appended at the end of a RESTful API endpoint. It can be identified by the question mark in front of them. For example, in the endpoint http://md5.jsontest.com/?text=test, "text" is a query parameter (with value "test"). · Path parameters are part of the RESTful API endpoint. For example, in the endpoint used earlier: http://ergast.com/api/f1/2017/circuits.json, "2017" is a path parameter value. If replaced with "2016" the previous test would fail, since there were 21 Formula 1 races in 2016, not 20. REST Assured can work with both types of parameters. First, it is mentioned how the query parameter from the above example can be used and specified. @Test public voidtest_Md5CheckSumForTest_ShouldBe098f6bcd4621d373cade4e832627b4f6() { String originalText = "test"; String expectedMd5CheckSum = "098f6bcd4621d373cade4e832627b4f6"; given(). param("text",originalText). when(). get("http://md5.jsontest.com"). then(). assertThat(). body("md5",equalTo(expectedMd5CheckSum)); } Using query parameters in REST Assured is as simple as specifying their name and value using the param(). Path parameters are specified similarly:
  • 14. 13 @Test public void test_NumberOfCircuits_ShouldBe20_Parameterized() { String season = "2017"; int numberOfRaces = 20; given(). pathParam("raceSeason",season). when(). get("http://ergast.com/api/f1/{raceSeason}/circuits.json"). then(). assertThat(). body("MRData.CircuitTable.Circuits.circuitId",hasSize(numberOfRaces)); } In the given case, the path parameters are defined using the pathParam() method rather than param(). In addition, defining the part of the endpoint path that represents the path variable is required, which is done using the curly bracket notation seen in the example above. This way, more than one parameter can be easily created and both the path and query parameters can be combined in a single call if the API supports or requires this. After creating this parameterized test, the next task would be to make it data-driven by using an external test data set. For ease, it is recommended to get it done with TestNG, even though Junit supports parameterization as well. TestNG is easier as it is only needed to create a DataProvider object containing the required test data as in this case it is the set of records containing years and number of Formula 1 races in each year. @DataProvider(name="seasonsAndNumberOfRaces") public Object[][] createTestDataRecords() { return new Object[][] { {"2017",20}, {"2016",21}, {"1966",9} }; }
  • 15. 14 The next step would be to pass the test data object to the parameterized test through test method parameters: @Test(dataProvider="seasonsAndNumberOfRaces") public void test_NumberOfCircuits_ShouldBe_DataDriven(String season, int numberOfRaces) { given(). pathParam("raceSeason",season). when(). get("http://ergast.com/api/f1/{raceSeason}/circuits.json"). then(). assertThat(). body("MRData.CircuitTable.Circuits.circuitId",hasSize(numberOfRaces)); } When dealing with a test data object, test cases can be added, removed or updated by creating, deleting or modifying the appropriate test data record. In a case where the test itself needs to be updated such as when the endpoint or the response body structure changes it is needed to update the test and all test cases will follow the updated procedure. 7.5 Accessing Secured APIs The security of APIs is often ensured with some or the other sort of authentication mechanism. REST Assured supports basic, digest, form, and OAuth authentication. The following example demonstrates how call a RESTful API that has been secured using basic authentication can be done (i.e., the consumer of this API needs to provide a valid username and password combination every time they call the API): @Test public void test_APIWithBasicAuthentication_ShouldBeGivenAccess() { given(). auth(). preemptive(). basic("username", "password"). when(). get("http://path.to/basic/secured/api"). then(). assertThat(). statusCode(200); }
  • 16. 15 Accessing an OAuth2-secured API pretty straightforward, given that you have a valid authentication token: @Test public void test_APIWithOAuth2Authentication_ShouldBeGivenAccess() { given(). auth(). oauth2(YOUR_AUTHENTICATION_TOKEN_GOES_HERE). when(). get("http://path.to/oath2/secured/api"). then(). assertThat(). statusCode(200); } 7.6 Passing Parameters Between Tests When testing RESTful APIs, it is often required to create more complex test scenarios when it is needed to capture a value from the resource of one API call and reuse it in a subsequent call. This is supported by REST Assured using the extract() method. The example here shows a test scenario that extracts the ID for the first circuit of the 2017 Formula 1 season and uses it to retrieve and verify additional information on that circuit (in this case, the circuit is located in Australia):
  • 17. 16 @Test public void test_ScenarioRetrieveFirstCircuitFor2017SeasonAndGetCountry_ShouldBeAustralia() { // First, retrieve the circuit ID for the first circuit of the 2017 season String circuitId = given(). when(). get("http://ergast.com/api/f1/2017/circuits.json"). then(). extract(). path("MRData.CircuitTable.Circuits.circuitId[0]"); // Then, retrieve the information known for that circuit and verify it is located in Australia given(). pathParam("circuitId",circuitId). when(). get("http://ergast.com/api/f1/circuits/{circuitId}.json"). then(). assertThat(). body("MRData.CircuitTable.Circuits.Location[0].country",equalTo("Australia")); } 7.7 Reusing Checks with ResponseSpecBuilder The reusability and maintainability of RESTful API tests can also be improved by reusing checks. For example, to check if all the API responses have a status code equal to 200 and a content type equal to "application/json,", it can be tiresome to specify this for each and every test. Another case considered, in addition, if for some reason the default status code and content type returned changes, it’d rather be affluent to only have to update this in one place, instead of throughout the test suite. Using the ResponseSpecBuilder mechanism, REST Assured supports reuse of specific verifications. The below example shows how a reusable Response Specification that checks aforementioned status code can be created and used in a test:
  • 18. 17 ResponseSpecification checkStatusCodeAndContentType = new ResponseSpecBuilder(). expectStatusCode(200). expectContentType(ContentType.JSON). build(); @Test public void test_NumberOfCircuits_ShouldBe20_UsingResponseSpec() { given(). when(). get("http://ergast.com/api/f1/2017/circuits.json"). then(). assertThat(). spec(checkStatusCodeAndContentType). and(). body("MRData.CircuitTable.Circuits.circuitId",hasSize(20)); } The checks that are specific to that test in addition to using the Response Specification can be created. 8. Benefits of REST Assured It is no doubt that REST Assured is a powerful library for API testing. Let’s see how: · It removes the need for writing a lot of boilerplate code which is required to set up an HTTP connection, send a request and receive and parse a response. · It supports a Given/When/Then test notation, which instantly makes tests human readable. · Since REST Assured is a Java library, integrating it into a continuous integration / continuous delivery setup is a breeze, especially when combined with a Java testing framework such as JUnit or TestNG.
  • 19. 18 For further illustration of the benefits of REST Assured, a simple REST Assured test is mentioned below. This test invokes a GET call to an API that, based on a zip code and a country code, provides some data on the location corresponding to that zip code. So, an example of the behavior of this API would look like this: · Given a specific country (in this case the India) and zip-code (in this case 110001) · When we perform a GET call to the RESTful API · Then the response returned indicates that the 110001 zip-code corresponds to New Delhi. 9. Other Salient Features of REST Assured REST Assured offers a number of useful features for writing RESTful API tests. 9.1 Technical Response Data Validation When checking if an API works as intended, it is not enough to just check response contents. For the application receiving the response, it is of importance that the response is technically sound; e.g., checking if the response has the right status code, header values, and formatting. All of these can be easily checked using REST Assured. For instance, to check if the response for a previously executed API call has a status code of 200 (indicating all is OK) and that the response header indicates that the body is to be interpreted as JSON, the following can be done: @Test public void checkHeaderData() { given(). pathParam("country","us"). pathParam("zipcode","90210"). when(). get("http://api.zippopotam.us/{country}/{zipcode}"). then(). assertThat(). statusCode(200). and(). contentType(ContentType.JSON); }
  • 20. 19 It is clear that with REST Assured, verifying technical response data is as straightforward as checking response body contents. 9.2 Data-driven Testing Another REST feature that makes API testing more powerful is its ability to create data- driven tests. For instance, if you want to check that zip code 12345 is associated with the city of Schenectady, New York. But instead of simply copying the entire test and replacing relevant parts, you would like to feed a single test with two different data records (this is called data-driven testing) to reduce potential maintenance efforts while making it easy to add even more tests. To do this, you will first need to create a test data set. This example uses the DataProvider object offered by TestNG: @DataProvider(name = "zipcodes") public String[][] createZipCodeTestData() { return new String[][] { {"us","90210","Beverly Hills"}, {"us","12345","Schenectady"} }; } Next, you will create a data-driven REST Assured test associated with this test data set: @Test(dataProvider = "zipcodes") public void aZipCodeTest(String country, String zipcode, String city) { given(). pathParam("country",country). pathParam("zipcode",zipcode). when(). get("http://api.zippopotam.us/{country}/{zipcode}"). then(). assertThat(). body("places.'place name'[0]",equalTo(city)); }
  • 21. 20 When you run this test, it'll be executed twice for each record in the test data set. It can be seen that creating data-driven tests in REST Assured is a straightforward step once you have tests in place for a single test data record. 9.3 Support for Authentication Mechanisms A lot of RESTful APIs require consumer authentication before interaction. REST Assured supports a number of commonly used API authentication mechanisms, including Basic (username and a password in the header of every call) and OAuth 2.0 authentication. Here’s how you can call a Basic authentication secured API with REST Assured. @Test public void checkBasicAuthentication() { given(). auth(). preemptive(). basic("username","password"). when(). get("http://mysecureapi.com/basicauth"). then(). assertThat(). body("authentication_result",equalTo("Success")); } There are several other useful features that REST Assured offers for creating powerful tests: · REST Assured has the ability to (de-)serialize Plain Old Java Objects (POJOs). This enables to serialize the properties and values associated with a Java object instance directly into a JSON or an XML document, which can further be sent to a RESTful API using the POST method. It works the other way around as well i.e. a JSON or an XML response returned by an API can be deserialized into a POJO instance by REST Assured as well. · Another interesting feature of REST Assured is Logging requests and responses. This can be especially useful when it is needed to inspect API responses to create the appropriate checks, or to make sure that the request being sent to an API is correct. Everything (parameters, headers, and body), only headers, only parameters, and much more can be logged. · REST Assured comes with a Spring Mock MVC module, which enables writing tests for Spring controllers using the REST Assured syntax.
  • 22. 21 10. Conclusion Today, almost all web applications use web services to communicate or interact with each other. Most modern-day web services are built on Representational state transfer (REST) architecture. REST’s popularity will only increase with time owing to its ease of use compared to other technologies. It is thus becoming imperative for software QA engineers, automation engineers, and software developers to understand the importance of web services testing and more importantly automating the process. Automating API tests is crucial for most projects due to the fact that API tests are far more stable, reliable, and fast. API automation with REST Assured is certainly the way forward in API testing. 11. About the Author Jaskeerat - Sr. Testing/QA Engineer TO THE NEW Jaskeerat Singh Ubhi is a ISTQB and Oracle Certified testing professional. He likes to invest time in learning automation testing tools and technologies. Jaskeerat is also interested and passionate about automating web and mobile applications 12. About TO THE NEW TO THE NEW is a premium digital technology company that provides end-to-end product development services. TO THE NEW leverages the power of experience design, cutting- edge engineering and cloud to build disruptive web and mobile products and enable digital transformation for businesses. TO THE NEW practices Agile methodologies to develop innovative products with a faster time to market. With a team of 750+ passionate technologists, TO THE NEW constantly challenges the status quo to empower Fortune 500 companies as well as startups across the globe.