REST API – Designing Business Logic Error Codes in HTTP Headers or Response Payload

http-responserest

I am designing a REST api backend that is meant to be consumed by a javascript front-end.

I am not sure how to communicate server-side business logic errors (e.g. a user trying to retrieve his password with an unknown email, etc.) to the front-end.

After setting a 40x status code on the response, I need to add further detail about the error and I am hesitating between two options:

  1. Setting custom HTTP headers in the response (e.g. X-Unknow-Email)
  2. Setting a JSON in the HTTP response payload with the corresponding error code

Can anyone having already being exposed to designing REST APIs please tell me what the pros and cons are for the two solutions being considered above?

Best Answer

I would say that option 2 makes it easier to understand what happened. The client can know to look in the body for a message, which is the usual place information is found. In your option 1, not only would the client need to know to look at the headers (which is more work in many rest client libraries), it would also have to know which headers to look for. In option 2, if need be, you can pass the string message to the user and let them figure out what it means. I think it is safe to assume that if you return an error code (non-2XX), then the client will not expect an entity in the response body, so it is ok to replace that with the message.

Related Topic