Interview #82: How to Validate the Status Code of an API Response Using RestAssured?

Interview #82: How to Validate the Status Code of an API Response Using RestAssured?

When testing APIs, validating the status code is one of the most fundamental checks. RestAssured, a popular Java-based API testing library, provides an easy way to verify that an API returns the expected HTTP status codes.

Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245

1?? What is a Status Code in API Responses?

Every API request returns an HTTP status code, which indicates the result of the request. Here are some common status codes:

? 200 OK – Successful request

? 201 Created – Resource successfully created

? 400 Bad Request – Client error (e.g., invalid input)

? 401 Unauthorized – Authentication required

? 403 Forbidden – User doesn’t have permission

? 404 Not Found – Resource doesn’t exist

? 500 Internal Server Error – API server error


2?? Validating the Status Code Using RestAssured

RestAssured provides multiple ways to assert the response status code. Below are different approaches:

?? Basic Validation of Status Code

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class StatusCodeValidationTest {
    public static void main(String[] args) {
        given()
            .when()
                .get("https://jsonplaceholder.typicode.com/posts/1") // Sample API
            .then()
                .statusCode(200); // Asserting that the response status code is 200
    }
}        

?? Explanation:

  • given() – Prepares the request
  • when().get(URL) – Sends a GET request to the API
  • then().statusCode(200) – Validates that the API returns HTTP 200 OK


?? Using Assertions for More Readable Validation

You can use Hamcrest matchers to improve readability:

given()
    .when()
        .get("https://jsonplaceholder.typicode.com/posts/1")
    .then()
        .assertThat().statusCode(is(200)); // Using Hamcrest's `is()` matcher        

The is(200) assertion ensures the status code is exactly 200.


?? Validating Multiple Status Codes (Using OR Condition)

Sometimes, an API may return different status codes based on conditions (e.g., 200 OK or 201 Created).

given()
    .when()
        .get("https://jsonplaceholder.typicode.com/posts/1")
    .then()
        .statusCode(anyOf(is(200), is(201))); // Accepts either 200 or 201        

This allows flexibility when an API can return multiple valid responses.


?? Capturing & Validating Status Code Dynamically

You can store the status code in a variable and validate it using assertions:

import io.restassured.response.Response;

public class StatusCodeCheck {
    public static void main(String[] args) {
        Response response = given()
            .when()
                .get("https://jsonplaceholder.typicode.com/posts/1");

        int statusCode = response.getStatusCode(); // Get status code dynamically
        System.out.println("Response Status Code: " + statusCode);

        if (statusCode == 200) {
            System.out.println("Test Passed: Status Code is 200");
        } else {
            System.out.println("Test Failed: Unexpected Status Code " + statusCode);
        }
    }
}        

?? Explanation:

  • .getStatusCode() – Retrieves the actual status code returned by the API.
  • Stores it in an int variable for further validation.
  • Uses conditional logic to check if the response is expected.


?? Using JUnit/TestNG Assertions for Automated Testing

For a proper automation framework, you should use JUnit or TestNG assertions:

? Using JUnit Assertion:

import static org.junit.Assert.assertEquals;
import io.restassured.response.Response;

public class APITest {
    @org.junit.Test
    public void testStatusCode() {
        Response response = given().when().get("https://jsonplaceholder.typicode.com/posts/1");
        assertEquals(200, response.getStatusCode()); // Validating expected vs actual
    }
}        

? Using TestNG Assertion:

import static org.testng.Assert.assertEquals;
import io.restassured.response.Response;
import org.testng.annotations.Test;

public class APITest {
    @Test
    public void validateStatusCode() {
        Response response = given().when().get("https://jsonplaceholder.typicode.com/posts/1");
        assertEquals(response.getStatusCode(), 200, "Status code does not match!");
    }
}        

Using assertions from testing frameworks allows automated validation in CI/CD pipelines.


3?? Handling Negative Cases – Validating Error Codes

APIs don’t always return success responses. We need to validate error status codes:

?? Validating 404 Not Found Response

given()
    .when()
        .get("https://jsonplaceholder.typicode.com/invalidEndpoint") // Non-existent URL
    .then()
        .statusCode(404); // Expecting "Not Found" error        

?? Validating 400 Bad Request Response

given()
    .queryParam("invalidParam", "test") // Sending an invalid parameter
    .when()
        .get("https://jsonplaceholder.typicode.com/posts")
    .then()
        .statusCode(400); // Expecting "Bad Request" error        

?? Validating Authentication Errors (401 Unauthorized)

given()
    .header("Authorization", "InvalidToken") // Sending invalid auth token
    .when()
        .get("https://api.example.com/protected-resource")
    .then()
        .statusCode(401); // Expecting Unauthorized response        

4?? Why is Status Code Validation Important?

? Ensures API responses align with expected behavior

? Helps detect unauthorized access, broken endpoints, and incorrect implementations

? Reduces false positives by validating only successful requests

? Essential for API automation in CI/CD pipelines


5?? Summary – Best Practices for Status Code Validation in RestAssured

? Always validate expected status codes in API tests

? Use Hamcrest matchers for better readability

? Store status codes in variables for dynamic validation

? Use JUnit/TestNG assertions for automated test execution

? Test both positive (200/201) and negative (400/404/500) scenarios


6?? Final Thought: Enhancing API Testing

While status code validation is essential, you should also check:

? Response body (JSON structure, key-value pairs)

? Response time (Performance benchmarking)

? Headers (Content-Type, authentication tokens)


要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章