g_m g_m - 1 month ago 8x
HTTP Question

HTTP status code 4xx vs 5xx

I am creating a REST API and find it difficult to choose the right HTTP status code to return in some cases.

Let's say I expect a certain value, and when it is not present I cannot perform a certain task and return an error. Because of the missing value the server cannot handle the request, but it was the client who sent it, wellformed but incomplete, in. Would it be best to return a

or a


It is totally upto you that what response you want to send to client.

But while sending a response you must be aware that it should be generic and clear about the incident which caused the request to fail.

Designing API is like desiging an agreement between the client and server. Server has to serve to client until that agreement or API specification is followed. It should clearly indicate in Api specification docs.

In your above case since server was accepting certain values with the request param and client did not sent it, it was fault of client since client did not agreed to api specification provided ahead of sending request.

In this case server should return HttpResponseStatus.BAD_REQUEST which is equal to 400 in code.

Tip: I would suggest you should not just return error code but also provide some error message with the response if any error occurs.


response : { errorCode:4xx, errorMessage:"Some thing went wrong"}