Rest – Should an HTTP API always return a body

api-designhttprest

Is there some sort of standard regarding HTTP API responses?

After reading this discourse thread I started to wonder. We are developing our public HTTP JSON API at my work, and we do not return anything when it's not strictly needed (for example a PUT to /resource/{id} only returns 200 when OK or the corresponding 4XX or 5XX code, but no JSON body)

Should we return a generic {"success":true} like they discuss on that link above, or is it ok to return a "void" body and handle everything with http response codes?

Best Answer

Regarding PUT, but applies to POST as well. The HTTP specification section 9 is a little empty on rules or even advice (SHOULD) when it comes to the scenario that you are describing. The line relevant to your question is most closely covered by:

If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

I do not think I would lose any sleep over it, but I would ask, what do you gain by adding the chunk of JSON into the response? You've just bulked out (OK, bulked might be overkill!) the response repeating less accurately what the status code should already have told you. If your PUT resulted in a new object return 201 (as is the intention of PUT), if it updated an object return 204.

Incidentally, API aside, instead of 200, if you don't return anything use 204.

Assuming that you are developing a set of RESTful interfaces, there is no standard per se, so whatever you do, document it well,, provide examples and everything will be alright.