Is It OK to Return HTML from a JSON API?

api-designbad codejsonrest

On my current project I am responsible for the implementation of a service which involves the consumption of newly created RESTful APIs, documented as solely supporting JSON.

The client consistently makes requests with the accept header of 'application/json' and content-type of 'application/json'. However some endpoints send a response with a content-type of HTML, even a HTML body. To me this is clearly the wrong approach and can never be justified.

Throughout the project this same practice has been applied across two different vendors and two different services. I found myself having to justify why the services needed to be changed. The vendors stated that the client should cope with this and even my REST library of choice has been questioned (RestEasy) because it doesn't cope with this by default 'out the box'.

This has been a major point of frustration. I can't find many references to back up my argument, I assume this is because the point is moot as it's so obvious.

The question is, am I missing something? am I being pedantic about this? Is it OK to have a JSON API that doesn't have a content-type of application/json in this scenario? References would be appreciated. How do you resolve this situation from a commercial point of view?

Best Answer

When you are sending an accept header requesting a specific media type, the server should not send back something else, and most certainly not with a 200 OK status code

From Restpatterns.org:

If no Accept header field is present, then it is assumed that the client accepts all media types. If an Accept header field is present, and if the server cannot send a response which is acceptable according to the combined Accept field value, then the server SHOULD send a 406 (not acceptable) response.

(Emphasis mine)

Restpatterns.org takes this from the actual HTTP standard: Header field definitions - Accept

In short: you are not being pedantic. The services are not following the HTTP standard if they are returning HTML when the accept header specifically tells them to return application/json and nothing else.