Rest Assured Tutorial Learn API Testing Step by Step

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 are 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.

https://www.soapui.org/testing-dojo/world-of-api-testing/what-makes-api-testing-special-.html

https://en.wikipedia.org/wiki/API_testing

REST vs SOAP

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:

http://searchsoa.techtarget.com/definition/REST [1]

http://blog.pluralsight.com/representational-state-transfer-tips [2]

https://www.soapui.org/testing-dojo/world-of-api-testing/soap-vs–rest-challenges.html [3]

http://blog.smartbear.com/apis/understanding-soap-and-rest-basics/ [4]

http://spf13.com/post/soap-vs-rest [5]

http://searchsoa.techtarget.com/tip/REST-vs-SOAP-How-to-choose-the-best-Web-service [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.

@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"));
 }

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(“”,””)
@Test
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
    builder.setBody(apiBody);

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

    //Making post request with authentication or leave blank if you don't have credentials like: basic("","")
    Response response = given()
        .auth()
        .preemptive()
        .basic({ username }, { password })
        .spec(requestSpec)
        .when()
        .post(restAPIUrl);
    
    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

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

  Response res = given()
     .contentType("application/json")
     .body("{\"name\":\"Onur Baskirt\"}")
     .when()
     .post("");

  String body = res.getBody().asString();
  System.out.println(body);
}

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

References:

https://rest-assured.io/[1] (Rest Assured GitHub page)

http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework/ [2]

http://static.javadoc.io/com.jayway.restassured/rest-assured/1.6.1/com/jayway/restassured/path/json/JsonPath.html [3]

http://www.javahotchocolate.com/notes/rest-assured.html [4]

http://artoftesting.com/automationTesting/restAPIAutomationPostRequest.html [5]

https://automationqahub.com/how-to-test-graphql-using-rest-assured/ [6] For GraphQL Testing with RestAssured.

API Testing Automation Examples

Example-1:

Test Description: Get the clients from https://generator.swagger.io/. We will do a GET request to get and print all clients.

Base URL: https://generator.swagger.io/

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

Example-2:

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.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>api-automation-basic</groupId>
    <artifactId>api-automation-basic</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <rest-assured-version>4.4.0</rest-assured-version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-path</artifactId>
            <version>${rest-assured-version}</version>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>${rest-assured-version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

TestNG.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="API Testing Suite" verbose="1">
    <test name="Nopackage">
        <classes>
            <class name="BasicApiTest"/>
        </classes>
    </test>
</suite>

I tried to explain the other codes line by line. Now I want to go on with the project’s JAVA files.

RestAssuredUtil.java

RestAssuredUtil.java 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 = "http://generator.swagger.io/";
    }

    //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) {
        given().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);
    }
}

TestUtil.java

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();
    }
}

BasicApiTest.java

We have some basic API tests in our test class.

import org.testng.annotations.Test;

public class BasicApiTest extends BaseTest {
    @Test
    public void T01_StatusCodeAndGetClientsTest() {
        res = utils.RestAssuredUtil.getResponse("/gen/clients");
        testUtil.checkStatusIs200(res);
        jp = utils.RestAssuredUtil.getJsonPath(res);
        System.out.println(testUtil.getClients(jp));
    }

    @Test
    public void T02_GetAndroidModelPackageOptions() {
        res = utils.RestAssuredUtil.getResponse("/gen/clients/android");
        testUtil.checkStatusIs200(res);
        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

https://github.com/swtestacademy/api-automation-rest-assured-basic  

Thanks for reading.
Onur Baskirt

87 thoughts on “Rest Assured Tutorial Learn API Testing Step by Step”

  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).

    Reply
  2. Hi Onur,

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

    Reply
  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.

    Reply
  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
    RestUtil.resetBaseURI();
    RestUtil.resetBasePath();
    }

    java.lang.IllegalArgumentException: baseURI cannot be null

    Reply
  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).

    Reply
  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?

    Reply
    • 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.

      Reply
  7. Hi.. It is a nice post..
    I recently tried a new framework ‘Karate’ for REST API automation.
    Below is the link
    https://github.com/intuit/karate
    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?

    Reply
  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.

    Reply
  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:

    //@Test
    public void test_07(){
    Response resp = given().
    param(“userid”,”40″ ).
    param(“user_id”, “72”).
    param(“token”, “any toekn”).
    when().
    get(“http://iloverestapitesting”);
    String actualUserReport = resp.
    then().
    contentType(ContentType.JSON).
    extract().
    path(“user_detail.email”);

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

    if(actualUserReport.equals(expectedUserReport)){
    System.out.println(“User Report API is working fine and test case pass”);
    }
    else{
    System.out.println(“User Report is not found and API is not working fine and test case failed”);

    }

    Reply
  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 ?

    Reply
  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.

    Thanks,

    Reply
  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.

    Reply
    • 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.

      Reply
  13. Hi Onur,

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

    Reply
  14. using “http://petstore.swagger.io/v2/pet/2” in browser, it showing response in XML.
    How to get response in JSON or it will be always XML in browser

    2
    string

    55
    prashant

    string

    available

    2
    string

    Reply
    • 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

      Reply
  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.

    Reply
  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?

    Reply
    • 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.

      Reply
  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
    Abdelhak

    Reply
    • 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.

      Reply
  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 :)

    Reply
  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”

    Reply
  20. Nice Article. Need your help in one weird issue I am facing with RestAssured to validate one GET call on BookStore API. It’s working fine in Curl..

    Working CURL Command as below:
    curl -X GET “https://bookstore.xxxx.com/Account/v1/User/f00600d9-dc34-46e7-84f1-9404410b7f74” -H “accept: application/json” -H “authorization: Basic Qm9va1Rlc3RlcjEyOlRlc3RlciMxMg==”

    AND It Returns JSON Response as expected.

    Now, I am calling same API using RestAssured with code as below:
    RestAssured.given().header(“accept”, “application/json”)
    .header(“authorization”, “Basic Qm9va1Rlc3RlcjpUZXN0ZXIjMTI=”)
    .when()
    .get(“https://bookstore.xxxx.com/Account​/v1​/User​/5641c9d9-1e3f-45be-a752-e1cc9d31e151”)

    But it’s not giving any JSON response but HTML default page.

    Please suggest.

    Reply
    • Hi, when you get the RestAssured response, you need to deserialize it with the response DTO class as shown below.

      First, you can convert response JSON to a DTO class from here: https://www.jsonschema2pojo.org/

      For, get and set methods, you can use Lombok Library’s @Getter and @Setter annotation to make the class leaner. Also, I suggest to use this annotation as well: @JsonIgnoreProperties(ignoreUnknown = true) for any kind of complication it will help.

      Assume that we named this class as BooksResponse.

      Then, you need to deserialize the Rest Assured response with this Response class as shown below.

      BooksResponse bookResponse;
      bookResponse = response.getBody().as(BooksResponse.class);

      and then when you converted the response as you can get and use any kind of values in it.

      If you want even JSON string, you can convert like below.

      Supplier OBJECT_MAPPER = () -> {
      final ObjectMapper mapper = new ObjectMapperConfigurer(new ObjectMapper()).getObjectMapper();
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
      mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
      return mapper;
      };

      /**
      * This method gives you json string from pojo.
      *
      * @param jsonObj pass jsonObject
      */
      static String getJsonStringFromPojo(final Object jsonObj) {
      try {
      return OBJECT_MAPPER
      .get()
      .writeValueAsString(jsonObj);
      } catch (final IOException e) {
      throw new IllegalStateException(e);
      }
      }

      I hope these hints will help and I will write a very comprehensive and advanced API automation framework article in the future. Keep checking swtestacademy blog. :)

      Reply

Leave a Comment

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