Udemy REST Assured free

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";
	
    @BeforeClass
    public void setup()
    {
        RestAssured.baseURI = "https://reqres.in/";
        RestAssured.basePath = "api";
    }
	
    @Test(enabled=true)
    public void pathParametersExample()
    {
         given()
             .queryParam("page", "2")
        .when()
            .get("/users/")
        .then()
            .statusCode(200)
            .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.

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