33

So I'm developing a Rest API

When a POST is made to create a resource and a required field is missing what should I return?

400 - Bad Request

OR

412 - Precondition Failed

And Why?

Charles
  • 50,943
  • 13
  • 104
  • 142
adamclerk
  • 759
  • 1
  • 6
  • 15
  • 1
    Does this answer your question? [When is it appropriate to respond with a HTTP 412 error?](https://stackoverflow.com/questions/5369480/when-is-it-appropriate-to-respond-with-a-http-412-error) – Michael Freidgeim Sep 20 '20 at 02:00

3 Answers3

41

Use 400 if the request parameters are wrong. Use 412 if one of the If-* request headers like If-Match, If-Modified-Since, etc are wrong.

Why? That's just what RFC says. See for example this extract of If-Match specification:

If none of the entity tags match, or if "*" is given and no current entity exists, the server MUST NOT perform the requested method, and MUST return a 412 (Precondition Failed) response. This behavior is most useful when the client wants to prevent an updating method, such as PUT, from modifying a resource that has changed since the client last retrieved it.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    It also states the request could not be fulfilled due to malformed syntax for 400. – Rob May 24 '12 at 04:00
  • 1
    This page really helped me - http://odino.org/don-t-rape-http-if-none-match-the-412-http-status-code/ - Using 'PUT' requests for context made it easier for me to understand what it's for, as it's always easy to abuse certain status codes. – Charlie Sep 15 '14 at 15:27
17

412 is used when your server does not meet a condition specified by the client.

In your case you should use a 400. It is just a bad request.

See this link for some explaination on pre-condition headers.

The Etag header is, generally, a string that represents our resource in the HTTP headers. You ask for a resource with an If-Match is a preconditional HTTP header. It will send a 412 if it does not match the code you sent.

If-None-Match tells the server to process a whole response only if the Etag is different from the one sent by the client.

nunespascal
  • 17,584
  • 2
  • 43
  • 46
4

You could use status code 422. If you don't want to, 400 is fine.

Julian Reschke
  • 40,156
  • 8
  • 95
  • 98