Skip to main content

Assertions on JSON response Code, Body and Headers using Rest Assured

You can assert response code, body and headers for API response using Rest Assured. Check below code:

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static org.hamcrest.Matchers.*;
import static io.restassured.RestAssured.given;

public class ReqRes 
    String id = "2";
    public void setup()
        RestAssured.baseURI = "";
        RestAssured.basePath = "api";
    public void pathParametersExample()
             .queryParam("page", "2")
            .body("total_pages", equalTo(2))
            .header("server", "cloudflare");

In above code .statusCode, Validate that the response status code matches. .body() Validate that the JSON response body conforms to one or more Hamcrest matchers. Here we are validating total_pages are equal to 2 in response. .header() Validate that a response header matches the supplied header name and hamcrest matcher.  Here we are validating server is equal to cloudflare in response heaader.

equalTo() Creates a matcher that matches when the examined object is logically equal to the specified operand. You need to import static org.hamcrest.Matchers.* to use this. In eclipse you manually needs to type import statement because it's a static import.

Submitted by tgoswami on September 2, 2020

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.