If you stumbled onto this article, it is safe to assume that you know what REST Assured is. REST Assured is built on top of Apache HTTP library and it adds more perks for those who are specifically interested in interacting with REST services. As such, it provides services, most of which are convenient, but sometimes they are deeply confusing when the things are not working out as REST Assured assumes they should.
The probability of things going wrong grows especially when the server side is not playing nice. For instance, I was working against REST API endpoint which returns JSON object. However, when I tried to access some of the values inside that object using standard tools, I got error of malformed JSON:
Test failed with: io.restassured.path.json.exception.JsonPathException: Failed to parse the JSON document
And printing out the response, I was surprised to see it wrapped with HTML tags, looking something like this:
<html> <body>{“success”: true, “field2”: “something” }</body> </html>
However, when I issued the same request from Postman or using curl, I received a correct JSON output, without HTML tags. So what gives? Luckily (or not), the REST server I am working with supports plain HTTP, so I was able to check the incoming traffic. The traffic also showed a pure JSON response, meaning that REST Assured was the one to change it.
Apparently, when the document comes with response header:
Content-Type: text/html
REST Assured automatically converts it into a valid HTML document, if some tags are missing. Therefore, in this case I needed to forcefully change the content type of the incoming output. This can be done by optionally attaching filter in a manner which resembles this one:
public void forceTreatResponseAsJson() {
RequestSpecification myRequest = // create the request
myRequest.filter(FORCE_JSON_RESPONSE_BODY);
}
static final Filter FORCE_JSON_RESPONSE_BODY = (reqSpec, respSpec, ctx) -> {
Response response = ctx.next(reqSpec, respSpec);
((RestAssuredResponseOptionsImpl<?>) response).setContentType("application/json");
return response;
};
Adding the REST Assured filter makes sure to alter the incoming response before it arrives to your code.