How to Validate Response in API Testing?

Ross Jackman | May 15, 2023

How to Validate Response in API Testing?

API testing is a testing type that mainly helps to determine whether an API’s functionality is working as expected and whether attributes like reliability, performance, and security meet the standard expectations.

It's also similar to black box testing since the software tester is primarily concerned about the input and output of an API tested and doesn’t need to know about the inner functionality of the application.

To validate the API response data (status code, size, body, headers, etc.), we can use below methods:

  • Assert: Below is the code for validating the status code of the GET request using the assertEquals() method:

    Response resp = get("- api endpoint url -");
    int statusCode = resp.getStatusCode();
    Assert.assertEquals(statusCode, 200); //200 is the status code for successful response

  • REST Assured: Below is the Rest Assured code for a GET request that can be used to validate a response:

    public void validation_test()
    {
    given()
    .header("Content-Type","application/json") // validate the header
    .when()
    .get("- api endpoint url -")
    .then()
    .statusCode(200); // validate the status code
    .body("data.id
    [indexValue]", equalTo(expectedValue)) // validate the id at the specified indexValue
    .body("data.first_name", hasItems("- content inside body -")); // validate multiple contents in the response body
    }

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment