REST Assured Validate HTTP Status Code

In this short REST Assured tutorial, you will learn how to validate HTTP Response Status Code when testing RESTful Web Service endpoint.

Every HTTP Response has a status code and depending on the status code value we can determine if HTTP Response was successful or not. Let’s have a look at how we can validate HTTP Response Status code with REST Assured.

Validate HTTP Response Status Code

Below is a code example which should produce a successful HTTP Response Status code 200. Provided that the URL path parameter of userId(tov5c2VC2c1RKXeM80rCtgXVmGN6Kj) is correct. If your Web Service Endpoint does not require Authorization Header, then simply do not set 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());
}

Notice that when using the Assert.assertEquals function

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

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

I will now provide an incorrect Authorization Header and will test for HTTP Status Code 403 which means Access Forbidden. The bellow Test method will also pass because if invalid Authorization Header is provided then the HTTP Response Status code will be 403.

@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 could also use a shorter version of code to validate the status code with REST Assured. Let’s say we have the below Test method which sends HTTP Get request to a public web service endpoint which does not require user authentication and authorization and thus does not need an authorization header to be provided.

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

I think you now have a good idea of how you can get the status code from HTTP Response using REST Assured and compare it to an expected value.

Check out other tutorials I have published on REST Assured and if you like learning by watching step-by-step video tutorials then check the list of video courses below. Hopefully one of them will help you learn faster and take your skills of Testing RESTful Web Services to a whole new level!