A Confused Programmer's Blog

This blog is dedicated to C# and Java programming that I happen to do for living – with accent on curious cases and with sincere intent to make the world of coding a slightly better place as a result

REST Assured and unexpected content types

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

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.

Comments are closed.

Subscribe to email feed

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

REST Assured and une

If you stumbled onto this article, it is safe to ...

Getting rid of Error

Since I upgraded my Windows 8 to Windows 10, I ...

Bypassing EULA step

We are working on automated testing of virtual appliance. This appliance ...

How I got rid of "Ac

OVF is a VMware virtual appliance format which allows you ...

My use-case of Perfo

In my blog I am set on a mission to ...

Twitter updates

RSS not configured