Search code examples
pythonweb-servicesresthttp-status-code-400http-status

Which HTTP Error code should a Web Service respond with when the consumer sends an incorrect request?


Say you have a REST service in Python/Flask that takes the following request body:

{'date': '2015-01-01'}

Your the consumer sends the following incorrect request:

{'date': '01/01/2015'}.

Your API fails to parse it, and you've captured the error and know the user sent the date in the wrong format. Which HTTP Error code do you respond with?

I've been using HTTP Code 400:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

I've told my consumer that if he sees 400, he should not attempt to resend the request because it needs to change first.

However, my consumer has been reporting that on occasion, my web server is returning a 400 error with the following HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

Sometimes my user gets this error message, even for a valid request, which I still cannot figure out. Now I am wondering if my use of 400 is incorrect. Notably, he cannot use the HTTP code alone to tell him if they should resend or not.


Solution

  • You can use either a status code 400 or 422 and provide some additional hints within the response payload. For example:

    {
      "errors": [
        {
          "field": "date",
          "message": "The format of the date must 'MM/dd/yyyy'"
        }
      ]
    }
    

    That way, the end user will know what is wrong within its request and update it.

    Hope it helps you, Thierry