Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http Status Code 400 vs 412

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?

like image 397
adamclerk Avatar asked May 24 '12 03:05

adamclerk


People also ask

What is a 412 status code?

The HyperText Transfer Protocol (HTTP) 412 Precondition Failed client error response code indicates that access to the target resource has been denied.

When should I use HTTP 412?

HTTP error 412 is used when you are using row versions or timestamps to avoid concurrency issues. If you sent the web service a record and include the row version in the header, the web service can compare that row version to the current row version.

How do I fix error 412?

Note : If you have a WordPress based website hosted over the server and have Bad Behavior plugin installed which is active, then you must first try deactivating it. This plugin is a PHP-based solution for blocking link spam and the robots which deliver it, which usually causes such an error in WordPress.

What is the HTTP status code 400?

The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).


2 Answers

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.

like image 128
BalusC Avatar answered Oct 04 '22 15:10

BalusC


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.

like image 45
nunespascal Avatar answered Oct 04 '22 15:10

nunespascal