Sunday 24 November 2019

Rest Assured: Extract value from response json


Using ‘extract().path()’ method, you can extract value from response json.

For example, API 'http://localhost:8080/api/v1/employees/3' return following response.

{
    "id": 3,
    "firstName": "Purna Chandra",
    "lastName": "Rao"
}

Below snippet extract firstName property value.

String firstName =
given()
         .header("Accept", "application/json")
.when()
         .get("api/v1/employees/3")
.then()
         .assertThat().statusCode(200).and()
         .contentType(ContentType.JSON)
.extract()
         .path("firstName");

TestApp.java
package com.sample.app;

import static io.restassured.RestAssured.given;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class TestApp {

 @Test
 public void testApp() {
  RestAssured.baseURI = "http://localhost:8080";

  String firstName = given().header("Accept", "application/json").when().get("api/v1/employees/3").then()
    .assertThat().statusCode(200).and().contentType(ContentType.JSON).extract().path("firstName");

  assertEquals(firstName, "Purna Chandra");
 }

}




Previous                                                    Next                                                    Home

No comments:

Post a Comment