6

Can someone please clarify what status codes should I expect from following situations? For instance, I am sending POST request with such body format:

{
  "id": 321,
  "username": "tombrown",
  "email": "tombrown@gmail.com",
  "password": "qwerty123",
  "activated": true 
}

So the questions are:

1) Should the server return 400 if I specify data of wrong type, for instance, "id": “threetwoone” instead of int, "activated": “yes” instead of boolean etc. Or server should rather return 422 here?

2) The “id” value should be int, but actually it is long int, e.g. 9223372036854774700.

3) Some fields are missing in the body, e.g. I try to send:

{
  "id": 321,
  "username": "tombrown",
  "activated": true 
}

Should these examples cause 400, 422 or some other options? What reaction should be correct?

Michael 12345
  • 85
  • 2
  • 5

1 Answers1

10

If the JSON is syntactically invalid, return 400. If JSON is syntactically valid but its content is invalid, return 422 to indicate that the request entity cannot be processed by the server.

See the following quote from the RFC 4918 (for your situation, just read JSON when it says XML):

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Thanks! Yes, the JSON is syntactically valid. Basically, I have a situation, when wrong data type causes a 500 error from the server, this confused me a bit. – Michael 12345 Apr 04 '18 at 10:23
  • @Michael12345 On my understanding, the syntax of the payload is still valid, however the server cannot process the entity. I would stick to `422`. – cassiomolin Apr 04 '18 at 10:35