Rest Assured Tutorial Learn API Testing Step by Step [2021]

Rest Assured is one of the most popular libraries which is highly used in API Test Automation in most companies. In this Rest Assured tutorial, I will try to explain Rest API, API Testing, API Automation, REST, and SOAP protocols.

Rest Assured Tutorial Outline

In this post, I will explain what is API and API testing, what is the difference between SOAP and REST services, and how to test REST APIs with Rest Assured Library.

What is API?

API stands for Application Programming Interface. It comprises a set of functions that can be accessed and executed by another software system.  Thus, it serves as an interface between different software systems and establishes their interaction and data exchange.

What is API Testing?

In the modern development world, many web applications are designed based on a three-tier architecture model. These are 1) Presentation Tier – User Interface (UI) 2) Logic Tier – Business logic is written in this tier. It is also called Business Tier. (API) 3) Data Tier – Here information and data are stored and retrieved from a Database. (DB) Ideally, these three layers (tiers) should not know anything about the platform, technology, and structure of each other.

We can test UI with GUI testing tools and we can test logic tier (API) with API testing tools. The logic tier comprises all of the business logic and it has more complexity than the other tiers and the test executed on this tier is called API Testing. API testing tests the logic tier directly and checks expected functionality, reliability, performance, and security.

In the agile development world, requirements are changing during short release cycles frequently and GUI tests are more difficult to maintain according to those changes. Thus, API testing becomes critical to test application logic. 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). These APIs generally REST APIs or SOAP web services with JSON or XML message payloads being sent over HTTP, HTTPS, JMS, and MQ.

[Ref: wiki] I don’t want to go into the theory so much in this post. If you want to learn more theory of API testing, you can visit the below websites.


REST (Representational State Transfer)

REST is an architectural style that uses simple HTTP calls for inter-machine communication. REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier, and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource. [1][2][6]

SOAP (Simple Object Access Protocol)

SOAP relies heavily on XML, and together with schemas, defines a very strongly typed messaging framework. Every operation the service provides is explicitly defined, along with the XML structure of the request and response for that operation. Each input parameter is similarly defined and bound to a type: for example, an integer, a string, or some other complex object. All of this is codified in the WSDL – Web Service Description (or Definition, in later versions) Language.

The WSDL is often explained as a contract between the provider and the consumer of the service. SOAP uses different transport protocols, such as HTTP and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifications to the SOAP protocol. [3][4][6]

References: [1] [2]–rest-challenges.html [3] [4] [5] [6]

REST API Testing with Rest Assured

What is Rest Assured?

In order to test REST APIs, I found the REST Assured library so useful. It is developed by JayWay Company and it is a really powerful catalyzer for automated testing of REST services. REST-assured provides a lot of nice features, such as DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads, and with those features, we will handle automated API testing much easier. Rest Assured has a gherkin type syntax which is shown below code. If you are a fan of BDD (Behavior Driven Development), I believe that you will love this kind of syntax.

 public void exampleRestTest() {
         .pathParam("id", "AskJsd8Sd")
         .body("firstName", equalTo("Onur"))
         .body("Surname", equalTo("Baskirt"));

Also, you can get JSON response as a string and send it to the JsonPath class and use its methods to write more structured tests. I generally prefer JsonPath for more structured tests.

@Test public void exampleJsonPathTest() {
    Response res = given().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"));

How to Make a POST Request with RestAssured?

The following code uses requestSpecBuilder to make a post request. Parameter descriptions are listed below.

  • restAPIURL – URL of the Rest API
  • APIBody – Body of the Rest API. Example: {“key1″:”value1″,”key2″:”value2”}
  • setContentType() – Pass the “application/json”, “application/xml” or “text/html” etc. headers to setContenType() method.
  • Authentication credentials – Pass the username and password to the basic() method or if there is no authentication leave them blank basic(“”,””)

public void httpPostMethod() throws JSONException, InterruptedException {
    //Rest API's URL
    String restAPIUrl = "http://{URL of API}";

    //API Body
    String apiBody = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";

    // Building request by using requestSpecBuilder
    RequestSpecBuilder builder = new RequestSpecBuilder();

    //Set API's Body

    //Setting content type as application/json
    builder.setContentType("application/json; charset=UTF-8");

    RequestSpecification requestSpec =;

    //Making post request with authentication or leave blank if you don't have credentials like: basic("","")
    Response response = given()
        .basic({ username }, { password })
    JSONObject JSONResponseBody = new JSONObject(response.body().asString());

    //Get the desired value of a parameter
    String result = JSONResponseBody.getString({ key });

    //Check the Result
    Assert.assertEquals(result, "{expectedValue}");

Gherkin Style Rest Assured POST Request

public void postExamplebyGherkin(){
  RestAssured.baseURI  = "Your API URL"; 

  Response res = given()
     .body("{\"name\":\"Onur Baskirt\"}")

  String body = res.getBody().asString();

For more theory, please visit references. I want to go with example questions and their solutions.

References:[1] (Rest Assured GitHub page) [2] [3] [4] [5] [6]

API Testing Automation Examples


Test Description: Get the clients from We will do a GET request to get and print all clients.

Base URL:

Resource Path: /gen/clients    

We will verify the status and print the clients which we get from the API.

api test automation with rest assured


Test Description: Get android clients. Then, check the status and print modelPackage.opt, modelPackage.description, and modelPackage.type values.

rest assured tutorial

API Testing Automation Solutions

Strategy: First, it is very reasonable to use a framework/library which provides us to test an API easily in a short period of time and we chose the Rest-assured library. It is better to write the code with the below rules.

Project Structure:

rest-assured basic example

We have utility functions and test classes. 

BasicAPiTest contains our test implementations.

I used TestNG as a test runner framework and all dependencies are in pom.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""


<!DOCTYPE suite SYSTEM "" >
<suite name="API Testing Suite" verbose="1">
    <test name="Nopackage">
            <class name="BasicApiTest"/>

I tried to explain the other codes line by line. Now I want to go on with the project’s JAVA files. It is a utility class for Rest Assured Library. It contains many methods that help us to write our codes more effectively.

package utils;

import static io.restassured.RestAssured.given;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

public class RestAssuredUtil {
    //Sets Base URI
    public static void setBaseURI() {
        RestAssured.baseURI = "";

    //Sets base path
    public static void setBasePath(String basePathTerm) {
        RestAssured.basePath = basePathTerm;

    //Reset Base URI (after test)
    public static void resetBaseURI() {
        RestAssured.baseURI = null;

    //Reset base path
    public static void resetBasePath() {
        RestAssured.basePath = null;

    //Sets ContentType
    public static void setContentType(ContentType Type) {

    //Returns response by given path
    public static Response getResponse(String path) {
        return given().get(path);

    //Returns response
    public static Response getResponse() {
        return given().get();

    //Returns JsonPath object
    public static JsonPath getJsonPath(Response res) {
        String json = res.asString();
        return new JsonPath(json);

We will get the clients and check the status code in this class.

package util;

import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.util.ArrayList;
import org.testng.Assert;

public class TestUtil {
    //Verify the http response status returned. Check Status Code is 200?
    public void checkStatusIs200(Response res) {
        Assert.assertEquals(res.getStatusCode(), 200, "Status Check Failed!");

    //Get Clients
    public <T> ArrayList<T> getClients(JsonPath jp) {
        return jp.get();

We have some basic API tests in our test class.

import org.testng.annotations.Test;

public class BasicApiTest extends BaseTest {

    public void T01_StatusCodeAndGetClientsTest() {
        res = utils.RestAssuredUtil.getResponse("/gen/clients");
        jp = utils.RestAssuredUtil.getJsonPath(res);

    public void T02_GetAndroidModelPackageOptions() {
        res = utils.RestAssuredUtil.getResponse("/gen/clients/android");
        jp = utils.RestAssuredUtil.getJsonPath(res);
        System.out.println("Opt: " + jp.get("modelPackage.opt"));
        System.out.println("Description: " + jp.get("modelPackage.description"));
        System.out.println("Type: " + jp.get("modelPackage.type"));

Let’s run our tests by right-clicking the TestNG.xml file and then click the to run option.

api automation

api testing

GitHub Project  

Onur Baskirt

84 thoughts on “Rest Assured Tutorial Learn API Testing Step by Step [2021]”

  1. Hi Onur,

    Good Blog on API testing with Rest-Assured..!!!

    Do you have any working example that you can illustrate on POST request passing the data dynamically ( read JSON file and pass in test script).

  2. Hi Onur,

    Very helpful article. Thank you for giving such an explanation with relevant examples. It really helped in my project.

  3. Can you please give an example how to post a complex Json post body (POST Method) with data provider. the Post body should be constructed with the values from dataprovider.

  4. Hi Baskirt,

    Thanks for detailed explanation. We are trying to implement the same. I am getting exception at ‘AfterTest’ method.

    Am i missing any configuration?

    public void afterTest (){
    //Reset Values

    java.lang.IllegalArgumentException: baseURI cannot be null

  5. Hi Onur,

    I am really happy that you have posted this article . Thank you so much for this article and it really helped me.

    Do you have any working example that you can illustrate on POST request passing the data dynamically ( read JSON file and pass in test script).

  6. Hi Onur, I’m thinking of using Rest Assured for my API testing, then I saw RunScope online where you can monitor tests and run tests + implementation of tests are easy. Do you know if Rest Assured is still to prefer or should I go for RunScope?

    • Hi Neda,

      If you want to use open-source solution you can use RestAssured. It is also not hard to use it and it has a significant community. When u get in trouble, you can find many blog articles or StackOverflow questions/answers. But If you want to go faster and much easier tool, you can go with Runscope. If I were you, I would try RestAssured for 2-3 weeks. If I could not reach my goals, then I switch to RunScope. But If you have very limited time and if you need to give a decision quickly, you can go on with RunScope.

  7. Hi.. It is a nice post..
    I recently tried a new framework ‘Karate’ for REST API automation.
    Below is the link
    They are claiming that it is a really good tool which is lot better than Rest-Assured. I am bit confused in choosing in between these two framework for our API automation.Could you please suggest is Karate really good.Or are there any drawbacks?

  8. I am using Version 0.1.9 of Rest Assured for .Net. I wanted to use https for sending the request instead of http.
    Please could you advice if there is some way to use https as UseHttps() is not working.

  9. @Onur Baskirt, Thanks alot.

    I really learned too much about restful api testing through your written, could you please help me out for connecting database to get expectedresult in below script:

    public void test_07(){
    Response resp = given().
    param(“userid”,”40″ ).
    param(“user_id”, “72”).
    param(“token”, “any toekn”).
    String actualUserReport = resp.

    String expectedUserReport = null;——>> help me out here for database connection

    System.out.println(“User Report API is working fine and test case pass”);
    System.out.println(“User Report is not found and API is not working fine and test case failed”);


  10. Hi Onur,

    It has been a very helpful article. thank you

    I am having a problem. when validating a schema, if a value returns null, rest assured throw assertion error. how can i fixed it ?

  11. HI Onur,
    1. Could you please let me can i Connect to Jenkins for CI? I need to run my APi every 10 mins and genrate reports and get email notification if response code is not 200?
    2. Does RA supports Database testing?
    3. My response content type is “text/xml” i am finidng most of the examples in JSON only. could u please give me some examples on XML, and XML methods??
    4. could u please give Data Driven example on RA from reading or validating from excel sheet? or extracting all url from excel sheet one after one.


  12. Hi Onur,
    Thank you for posting this clean and basic project example. I have a question though, in Example-1.class and Example-2.class you are running the same SetUp() method. Is there any smart way to make both test suites to use same SetUp() function?
    Thanks in advance.

    • Hi Gökçe, of course, there is a smart way to combine setup methods. :) One of the most common ways is to write a BaseTest class and then extend it in test classes like Page Object Model. There are some problems in my code.

      1- Test classes should have only test methods.
      2- It is better to write common setup and teardown methods in BaseTest class.

  13. Hi Onur,

    This is a great article on API testing. Also went through your couple of articles and they are very handy.

  14. using “” in browser, it showing response in XML.
    How to get response in JSON or it will be always XML in browser






    • Thanks ,Can we do both web service and API testing using rest assured ,As far I know using Soap UI we can test both.
      Which has more features Soap UI or rest assured and which is easy to use

  15. Hi I think your approach will be bit difficult to maintain if my response json will be huge we have to write json path to extract the JSON.

    Instead why don’t we go for model class mapping way(pojo class) map your response with model class from that we can extract the data.

  16. Hi Onur, Thank you for your tutorial, I am starting to learn API testing but there are many tools and I don’t know how to start manual, then automated?!
    I saw many tutorials but, you know, none of them start similar to you from zero points, could you please let me know if you know any good resource? my colleague recommended starting with the postman, what is your idea?

    • Yes you can use POSTMAN to check the endpoints and their functionality. After that check the responses in JSON viewer websites online. After that, you can start to automate them even using POSTMAN or writing a JAVA project with Rest-Assured or Rest Template or OKhttp or similar libraries. I suggest Rest-Assured because it is very QA friendly. I hope this helps.

  17. Hello,
    I want to automate API testing and i’m really confused between rest assured and postman as postman also provide newman to automate CI/CD using scripting.
    Do you think that Rest assured is better than postman?

    Thank you

    • Hello, we are using POSTMAN for exploratory testing of APIs but also you can use it for automated way. On the other hand, we are using rest assured for automation because it gives us full flexibility and maintainability. If you have a very modular and maintainable framework, you can implement further changes easily with minimal effort.

  18. Hi Onur, hope you are doing good!
    Can you please suggest me any article related to RestAssured in C# (BDD Specflow)
    Mainly when the request body is of “x-www-form-urlencoded” format.
    Thank you in advance :)

  19. Thnx Onur for the article. it really helped me in understanding.

    In case any one here faces any problem like “testng-error-cannot-find-class-in-classpath” use package name before class name in testng.xml like -> ” TestClass.BasicApiTest”


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.