Validate HTTP Status Code: RestAssured

This short REST Assured tutorial will teach you how to validate the HTTP Response Status Code while testing a RESTful Web Service endpoint. Each HTTP Response includes a status code, and by examining the status code value, we can determine if the HTTP Response was successful or not. Let’s explore how we can use REST Assured to validate the HTTP Response Status code.

If you’re interested in discovering how to return a custom status code from a Spring Controller, take a look at “Return Custom HTTP Status from Spring Controller

What is REST Assured?

REST Assured is a Java-based library that provides a simple and intuitive way to test RESTful web services. It enables you to perform HTTP requests and validate the responses in a fluent, expressive syntax that makes it easy to read and understand your tests.

REST Assured is built on top of the popular testing framework, JUnit, and integrates seamlessly with other Java-based tools like Maven and Gradle. It supports all major HTTP methods, including GET, POST, PUT, DELETE, and PATCH, and provides a range of validation methods to test different aspects of your API responses.

Why use REST Assured?

There are several benefits to using REST Assured for API testing:

  1. Easy to learn: REST Assured has a simple and intuitive syntax that is easy to learn, even for testers who are new to Java or API testing.
  2. Fluent interface: The fluent interface of REST Assured allows you to write readable and concise tests, making it easier to understand and maintain your test suite.
  3. Integration with JUnit: REST Assured integrates seamlessly with JUnit, one of the most popular testing frameworks in the Java ecosystem, making it easy to integrate API testing into your existing testing workflow.
  4. Built-in assertions: REST Assured provides a range of built-in assertions that allow you to test different aspects of your API responses, such as status codes, response headers, and response bodies.
  5. Extensibility: REST Assured is highly extensible and can be customized to meet the specific needs of your API testing requirements. You can write custom matchers, filters, and parsers to handle complex scenarios and edge cases.

By using REST Assured, you can streamline your API testing process, reduce the time and effort required to write and maintain tests, and ensure the quality and reliability of your API endpoints.

HTTP Status Codes

HTTP status codes are three-digit codes returned by web servers to indicate the status of a request. They are important in API testing because they provide information about whether a request was successful or not. There are five categories of HTTP status codes:

  1. 1xx (Informational): These codes indicate that the server has received the request and is continuing to process it.
  2. 2xx (Successful): These codes indicate that the request was successfully received, understood, and accepted.
  3. 3xx (Redirection): These codes indicate that the client must take additional action to complete the request.
  4. 4xx (Client Error): These codes indicate that the request was invalid or could not be processed by the server due to client error.
  5. 5xx (Server Error): These codes indicate that the server encountered an error while processing the request.

Some of the most common HTTP status codes that you might encounter when testing RESTful web services include:

  1. 200 OK: This code indicates that the request was successful and that the server has returned the requested data.
  2. 201 Created: This code indicates that a new resource has been successfully created on the server.
  3. 400 Bad Request: This code indicates that the client has sent an invalid request to the server.
  4. 401 Unauthorized: This code indicates that the client is not authorized to access the requested resource.
  5. 404 Not Found: This code indicates that the requested resource could not be found on the server.
  6. 500 Internal Server Error: This code indicates that the server encountered an error while processing the request.

When testing RESTful web services, it’s important to understand the meaning of these codes and how to interpret them. By validating HTTP status codes in your tests, you can ensure that your APIs are functioning as expected and that your clients are receiving the correct responses.

Handle different HTTP status codes

In REST Assured, validating the HTTP response status code is crucial when testing your API. HTTP status codes indicate whether a request has been successfully processed or if there was an error, providing valuable information about what went wrong. To handle different HTTP status codes in your tests, you can use the given() method provided by REST Assured.

The given() method sets up the preconditions for your test by specifying the HTTP request, such as the HTTP method, headers, and parameters. It is used at the beginning of the test, and it allows you to configure the request before sending it. Here’s an example:

given()
  .param("userId", "123")
  .header("Authorization", "Bearer token")
  .when()
    .get("/users")
  .then()
    .statusCode(200);

In the example above, we are sending a GET request to the “/users” endpoint with a user ID parameter and an authorization header containing a bearer token. We then validate that the response status code is 200 OK. If the response status code is not 200, the test will fail.

You can also validate other HTTP status codes, such as 201, 204, 400, 401, 403, 404, 500, etc. Here’s an example of how to validate a 404 Not Found status code:

given()
  .when()
    .get("/users/999")
  .then()
    .statusCode(404);

In addition to validating the HTTP status code, you can also check the response body and headers to ensure that they meet your expectations. This can be done using the body() and header() methods provided by REST Assured. Here’s an example:

given()
  .when()
    .get("/users/123")
  .then()
    .statusCode(200)
    .body("firstName", equalTo("John"))
    .body("lastName", equalTo("Doe"))
    .header("Content-Type", containsString("application/json"));

In the example above, we are validating the HTTP status code, the first name and last name fields in the response body, and the content type header.

Validate HTTP Response Status Code

The code example below is designed to generate a successful HTTP Response Status code 200, provided that the URL path parameter of userId (tov5c2VC2c1RKXeM80rCtgXVmGN6Kj) is accurate. If your Web Service Endpoint doesn’t require an Authorization Header, you can skip setting the Header value in your code.

@Test
public void validate_response_status_code_200() {
    
    Header authorizationHeader = new Header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0OUB0ZXN0LmNvbSIsImV4cCI6MTUyNjY1NDgzMn0.Tmv4blwxuiMIZzKar6uLNOKPRDIDJ6nGBPwy6UauNi287dEl0xZCD31SUCfXhVpqJcZdY4JlX99RihAiRj-mIQ");
    RequestSpecification httpRequest = RestAssured.given();
    httpRequest.header(authorizationHeader);
    
    Response response = httpRequest.get("/tov5c2VC2c1RKXeM80rCtgXVmGN6Kj");
    Assert.assertEquals(200, response.getStatusCode());
}

It should be noted that when utilizing the Assert.assertEquals function:

Assert.assertEquals(200, response.getStatusCode());

The expected value is provided as the first method parameter, and the second method parameter is the actual value.

I will intentionally provide an incorrect Authorization Header and verify if the HTTP Status Code 403 (Access Forbidden) is returned. The following Test method will pass because a 403 code will be generated in response to an invalid Authorization Header.

@Test
public void validate_response_status_code_403() {
    
    Header authorizationHeader = new Header("Authorization", "Bearer invalid-authorization-header");
    RequestSpecification httpRequest = RestAssured.given();
    httpRequest.header(authorizationHeader);
    
    Response response = httpRequest.get("/tov5c2VC2c1RKXeM80rCtgXVmGN6Kj");
    Assert.assertEquals(403, response.getStatusCode());
}

You can use a shorter code version to validate the status code using REST Assured. For example, consider the following test method that sends an HTTP GET request to a public web service endpoint that does not require user authentication or authorization and therefore does not need an authorization header.

get("/status/check").then().assertThat().statusCode(200);

Validate Multiple HTTP Status Codes

In some cases, you may want to validate multiple HTTP status codes in a single test. For example, you may want to ensure that your API returns different status codes for different scenarios, such as successful requests, invalid requests, and unauthorized requests. REST Assured provides several ways to achieve this.

Using the assertThat() Method

One way to validate multiple HTTP status codes is by using the assertThat() method provided by REST Assured. The assertThat() method allows you to specify multiple assertions for a single response, including assertions for the HTTP status code. Here’s an example:

given()
  .when()
    .get("/users/123")
  .then()
    .assertThat()
      .statusCode(anyOf(is(200), is(304), is(404), is(500)));

In the example above, we are sending a GET request to the “/users/123” endpoint and validating that the response status code is either 200 OK, 304 Not Modified, 404 Not Found, or 500 Internal Server Error. If the response status code is not one of these codes, the test will fail.

Using the or() Method

Another way to validate multiple HTTP status codes is by using the or() method provided by REST Assured. The or() method allows you to specify multiple assertions for a single response, separated by the logical OR operator (||). Here’s an example:

given()
  .when()
    .get("/users/123")
  .then()
    .statusCode(is(200).or().is(304).or().is(404).or().is(500));

In the example above, we are sending a GET request to the “/users/123” endpoint and validating that the response status code is either 200 OK, 304 Not Modified, 404 Not Found, or 500 Internal Server Error. If the response status code is not one of these codes, the test will fail.

Using Multiple Assert Statements

Finally, you can validate multiple HTTP status codes by using multiple assert statements in a single test. Here’s an example:

given()
  .when()
    .get("/users/123")
  .then()
    .statusCode(is(200)));

given()
  .when()
    .get("/users/999")
  .then()
    .statusCode(is(404)));

given()
  .when()
    .get("/users")
  .then()
    .statusCode(is(401)));

In the example above, we are sending three GET requests to different endpoints and validating that each response status code is correct. If any of the response status codes are incorrect, the corresponding test will fail.

Best Practices for Validating HTTP Status Codes

When testing RESTful web services with REST Assured, validating HTTP status codes is a critical part of ensuring that your API is functioning correctly. Here are some best practices to keep in mind when validating HTTP status codes in REST Assured:

  1. Validate the HTTP status code first: Always validate the HTTP status code before parsing the response body. This ensures that you’re testing the right thing, and can help you identify issues more quickly if the status code is incorrect.
  2. Use meaningful error messages: When an HTTP status code validation fails, it’s important to provide a meaningful error message that explains what went wrong. This can help you troubleshoot failed tests more quickly and accurately.
  3. Use descriptive test names: Give your tests descriptive names that make it easy to understand what they’re testing. For example, “testCreateUserSuccess” is more informative than “test1”.
  4. Use constants or enums for HTTP status codes: To make your code more readable and maintainable, consider using constants or enums for HTTP status codes. This can help you avoid typos and ensure that your tests are consistent.
  5. Be consistent with your HTTP status code assertions: Choose an assertion method that works well for you, and use it consistently across all of your tests. This can help you avoid errors and make it easier to maintain your tests.
  6. Test both success and failure scenarios: Don’t just test for success scenarios – also test for failure scenarios like 404 Not Found or 500 Internal Server Error. This can help you identify issues before they impact your users.

By following these best practices, you can write more effective tests and ensure that your RESTful web services are functioning as expected.

Frequently asked questions

  • Can I use REST Assured to test APIs other than RESTful web services?
    REST Assured is primarily designed for testing RESTful web services, but it can also be used to test other types of APIs such as SOAP and GraphQL. However, it may require some additional configuration and customization depending on the API type.
  • What’s the difference between Assert.assertEquals and RestAssuredMatchers.equalTo?
    Assert.assertEquals is a JUnit assertion that compares two objects for equality, while RestAssuredMatchers.equalTo is a REST Assured assertion that compares the response body to an expected value. In general, you should use Assert.assertEquals to compare objects and RestAssuredMatchers.equalTo to compare response bodies.

Conclusion

By now, you should have learned how to extract the status code from an HTTP response using REST Assured and verify that it matches an expected value.

Want to become proficient in testing RESTful web services? Head over to the Testing Java Code page, where we provide an in-depth tutorial on utilizing REST Assured. Learn how to effectively test your APIs, validate responses, and handle authentication and authorization.

If you prefer learning through step-by-step video tutorials, then browse the list of video courses below. With any luck, one of these resources will help you accelerate your learning and elevate your skills in testing RESTful web services.


Leave a Reply

Your email address will not be published. Required fields are marked *