Parse the JSON response body using JsonPath class in REST Assured

Profile picture for user devraj

JsonPath is an alternative to using XPath for easily getting values from a Object document. It follows the Groovy GPath syntax when getting an object from the document. You can regard it as an alternative to XPath for JSON.

Consider Below Example:

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

public class ReqRes 
{	
    @BeforeClass
    public void setup()
    {
        RestAssured.baseURI = "https://reqres.in/";
        RestAssured.basePath = "api";
    }
	
    @Test(enabled=true)
    public void postRequestExample()
    {
        String res = 
        given()
            .body("{" + 
                "    \"name\": \"Tarun\",\n" + 
                "    \"job\": \"Goswami\"\n" + 
                "}")
			  
        .when()
            .post("/users")
        .then()
            .statusCode(201)
            .extract().response().asString();
		
        JsonPath js = new JsonPath(res);
        String id = js.getString("id");
        System.out.println("id is:"+id);
    }
}

In above code we got the id using JsonPath object and method getString. This case is useful when you want to re use this id further in your program.