3

In my web service I am processing input as json. What is the correct HTTP status code to use when the provided input is invalid, particularly for PUT and POST requests?

The only response code I can find that seems to apply is "400 Bad Request", but maybe there is something better?

I actually have two possibly different specific cases of this question:

a) The server doesn't like the JSON input because the attributes/ values cannot be accepted, or
b) The server cannot parse the JSON formatted input because the data is not correctly formatted as JSON.

Example: If the server expects

{ 
  "POSTDATA": {
     "val1":"123", 
     "val2":"xyz"
   }
}

and the client gives something we don't know what to do with

{ 
    "val1":"bar", 
    "val2":"biz"
}

or the client gives something borked, eg

{
"valA":"123",
skjfhasklfhakppffffzzzzz....

What to do?

The Tahaan
  • 6,915
  • 4
  • 34
  • 54
  • 2
    I think this might elicit some strong opinions on different sides. I don't think a Bad Request code is appropriate, as that *to me* suggests that the HTTP request is bad - which it is not. I suspect others will disagree strongly. I'm not sure I'll put it on-hold as such just now, though; maybe there's a strong standard here? – Andrew Barber Nov 06 '14 at 14:13
  • 1
    possible duplicate of [Right HTTP status code to wrong input](http://stackoverflow.com/questions/7939137/right-http-status-code-to-wrong-input) – Laurent S. Nov 06 '14 at 14:14
  • Your first error example would be a candidate for *422 Unprocessable Entity* – Alex K. Nov 06 '14 at 14:16

2 Answers2

1

415 Unsupported media type. The origin server is refusing to service the request because the payload is in a format not supported.

Amjad Alwareh
  • 2,926
  • 22
  • 27
  • 3
    I don't like this. If the request specified application/text and the server requires application/json, then Yes 415 is the correct response. But if the application provides invalid json, but correctly specifies `application/json`, then the response should not be "try another media type" which is what I understand 415 to mean, it should say "your media type is correct but the data is corrupted / invalid. So I have eventually just settled on 400 invalid request. The only issue is that I use the same code for an invalid request taht is invalid based on business requirements. – The Tahaan Sep 10 '19 at 13:20
0

This is an ancient question now, but for what it's worth: Today (thanks to WebDAV http extensions), this error can best be served with a 422 (Unprocessable Entity) error code, as the format and syntax are correct, but the data itself cannot be used for its intended purpose.

Mike Fahy
  • 5,487
  • 4
  • 24
  • 28