Skip to main content

Parse the JSON response body using JsonPath class in REST Assured

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.

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.

About

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.