Home > other >  Status code inside the body of a REST API response
Status code inside the body of a REST API response

Time:11-13

I have seen a lot applications using REST API returning a status code inside theirs response bodies, although the HTTP response returns the status code just fine. Is there any reason to put the status code also in the body of the response?

CodePudding user response:

Some APIs return a 200 for all requests, even erroneous ones, and put a status code in the response body. This status code might mimic HTTP status codes, but doesn't have to. One could start numbering your response statuses from 1 for all anyone cares.

Other APIs return appropriate HTTP status codes, and indeed, put the same status code in the response. That's just a waste of bandwidth and brain cells, and a cause for lots of head scratching. It's unnecessary. Except...

It might be useful for some kinds of client libraries. When a client application uses a library that abstracts away all the HTTP stuff, it can just return an object to the programmer that contains all information about the response.

Something like:

{
    "status": 200,
    "data": {
        "foo" : "bar"
    }
}

And:

{
    "status": 401,
    "data": null,
    "message": "You are not authorized."
}

This way the library author can chuck the HTTP status code into the object's status property, and the caller doesn't have to deal with exception handling.

But then still there's no reason for the API to respond with it both in HTTP status code and response.

CodePudding user response:

Is there any reason to put the status code also in the body of the response?

Yes, in the sense that the status-line is HTTP metadata, describing the semantics of the response message. Like other HTTP metadata, it's not really designed for use by the end client.

Consider the web experience - the browser gets to see the HTTP response message, and can act on it. But what information do you want to share with the user? In cases where you wanted the user to be aware of the HTTP status code, you would include it in the HTML representation also.

Problem Details for HTTP APIs includes an optional status field in its schema to surface that information for the client.

  • Related