REST Assured Get HTTP Response Body

In this short tutorial on REST Assured you will learn how to get the entire HTTP Response Body when testing your RESTful Web Service Endpoint.

Web Service Endpoint Response

Let’s assume we have the following Web Service Endpoint URL and when HTTP GET request is made to this Web Service Endpoint a JSON representation of user details is returned in HTTP Response Body:

URL:

http://localhost:8080/api/users/tov5c2VC2c1RKXeM80rCtgXVmGN6Kj

JSON representation of the returned user details:

{
 "firstName":"Sergey",
 "lastName":"Kargopolov",
 "id":"tov5c2VC2c1RKXeM80rCtgXVmGN6Kj"
}

REST Assured Test Method to Display Response Body

Let’s have a look at an example of a Test method which will use REST Assured to send HTTP GET request to the above mentioned Web Service Endpoint and display the HTTP Response Body.

public class UsersAPITest {

    @Before
    public void setup() {
        RestAssured.baseURI = "http://localhost:8080/users";
    }
    
    @Test
    public void givenUrl_display_response_body() {
        
        Header authorizationHeader = new Header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0OUB0ZXN0LmNvbSIsImV4cCI6MTUyNjY1NDgzMn0.Tmv4blwxuiMIZzKar6uLNOKPRDIDJ6nGBPwy6UauNi287dEl0xZCD31SUCfXhVpqJcZdY4JlX99RihAiRj-mIQ");
        RequestSpecification httpRequest = RestAssured.given();
        httpRequest.header(authorizationHeader);
        
        Response response = httpRequest.get("/tov5c2VC2c1RKXeM80rCtgXVmGN6Kj");
     	
        System.out.println("Response Body is =>  " + response.asString());
    }
}

and the result printed into a console is:

Response Body is =>  {"id":"tov5c2VC2c1RKXeM80rCtgXVmGN6Kj","firstName":"Sergey","lastName":"Kargopolov"}

Please notice a few things above the above Test method:

  • To get the Response object from the HTTP Request(RequestSpecification), I used:
    Response response = httpRequest.get("/tov5c2VC2c1RKXeM80rCtgXVmGN6Kj");
  • Then, once we have the Response object we can easily get its body as a String by either:
    response.getBody().toString()

    or

    response.asString()

    and then print it out as in my code example with System.out.println().

  • Also, notice that I had to use Header object. This is because in my Web Service Endpoint I have Spring Security configured. This is why all my RESTful Web Service endpoints are protected with JSON Web Token and require user authentication and then authorization. If your Web Service Endpoint does not require user authorization with JSON Web Token, then simply do not provide Header information.

I hope this short tutorial on how to display the content of HTTP Response Body with REST Assured was helpful for you. Check out other tutorials I have published on REST Assured and if you enjoy learning by watching step-by-step video lessons, then check out the below list of video courses.