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.

Video Tutorial


Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.