3

I'm developming RESTful API service. I've got disagreement between Me and my Team Lead, on the subject: "HTTP Response status codes".

My Team Lead talks, that default HTTP status codes written in RFC is awful and it's very hard to handle them on the client side(frontend). He thinks that custom status codes in response body, with HTTP status code 200 (every time 200) - the best way. His response body will like following, when trying to execute action without permissions:

HTTP/1.1 200 OK

{
    code: 1005,  // Custom code instead 403
    data: {
        message: "Forbidden."
    }

}

I think that is wrong way to response. My response scheme will be like this:

HTTP/1.1 403 Forbidden

{
    code: 403,
    success: false,
    message: "Forbidden."

}

Should we use RFC HTTP status codes, or we can use our own custom? Where is the best and right way?

Mully
  • 233
  • 1
  • 10

1 Answers1

4

The short

You are absolutely right.

The long answer

In restful API design you have to make use of the official HTTP codes specified in RFC-7231. Please do not send a 200 OK for every request. 200 OK is reserved for requests which actually succeeded and the server responds with a valid state of a particular resource. There are codes for most use cases. If you still need to differ errors of the same type, for example FORBIDDEN you may send a custom error code along. But the HTTP response is still an error therefore you shall not use 200 OK.

Regarding your proposed error scheme, you should not send the code and status within the body. This is already sent as the HTTP status and therefore redundant. Also a boolean success flag is redundant since the type of HTTP code already points out if it was a success or not (2xx => success, 4xx client error, 5xx server error). The body should contain additional context which will help an API client to resolve the problem.

A well designed API error response should contain helpful information to fix a possible problem:

  • Request ID which gets generated per request on the server
  • Detailed error message
  • (Optional) Internal error code
  • (Optional) Error category
  • (Optional) Reference to the api documentation/error description

Example:

HTTP/1.1 403 Forbidden
{ 
    "requestId": "a5e5dd13-0047-4d2e-b96c-55a5031f0511", 
    "message": "You are not allowed to access this resource. Missing write permission.",
    "category": "AccessControl"
}

If this still is not enough for your team lead to believe you may point out some well designed REST API's:

Community
  • 1
  • 1
raffis
  • 546
  • 1
  • 5
  • 18