What is the http status code when Api raises ValueError?

Question:

I am raising Value Error in my API because the input parameter of a particular function is not valid like below

  1. Password doesn’t match
  2. User doesn’t exist in db or the value is negative

Client provided valid argument as per the API norms so I think Client side error is not the case(400 series code).

So whether I have to return status code as 200 because that request is totally processed or there should be a http status code for this.

Asked By: Anand Tripathi

||

Answers:

You should send another status code.

A good example of a processed request which gives another status than 200 is the redirection 3xx. After submitting a form through a POST request, it is recommended that the server gives a 307 Temporary Redirect. However, the request was totally processed, and even succeeded.

In your case, something happened (an exception has been raised). Let the client know it by sending a adequate status. I would recommend 403 Forbidden or 401 Unauthorized.

Answered By: Dunatotatos

As there are various invalid types, you should use the most appropriate HTTP status code for each different situation, case by case.

For Password doesn't match, I think 403 Forbidden is the best choice.

For User doesn't exist in db, 204 No Content is the best one.

For value is negative, it depends on why value is negative.

Answered By: shaochuancs

You probably should return something from the 4xx range to indicate that there is something wrong with the request that prevents the request from being executed. 400 (bad request) is what you use for failed input validation. For problems with authentication or password, 401 (Unauthorized) is the most appropriate. If the user is authenticated but is not allowed to do particular things, use 403 (Forbidden). If the problem is with an object that does not exist (like a user), you can return a 404 (Not Found).

2xx response codes are used to indicate the request was received and processed successfully, 3xx are used to tell the user that nothing happened but that there is some alternate request that can be performed (e.g. redirect for 301 and 303, or not modified 304). 5xx is reserved for signaling various problems on the server side that prevent the request from being executed.

Wikipedia has a good overview of common http response codes and their meaning.

Answered By: Jilles van Gurp

For a typical ValueErrors, which your first two examples don’t fit into, you could use for if a value is negative:

406 Not Acceptable

422 Unprocessable Entity

Answered By: run_the_race