views:

49

answers:

5

Hey,

I'm implementing an API. The API accepts/returns JSON content type. Now, suppose that the data submitted by some POST request is not valid, like a missing attribute, or a duplication exists for the same data. What is the standard HTML response code in that case?

A: 

The closest i can find would be 400 Bad Request.

cHao
+2  A: 

The error lies on the client side, so you want to use a 4xx status code. I'd go with 400 - Bad Request:

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

Frédéric Hamidi
+1  A: 

There are two answers:

If you have submitted a form, just return 200 - OK with HTML explaining why the object was not created.

If you have an API you should use the following

200 OK

  • When the request was OK and returned the proper data.

201 CREATED

  • The call was successful and the new object created.

400 BAD REQUEST

  • Invalid request URI
  • Invalid HTTP Header
  • Receiving an unsupported, nonstandard parameter
  • Receiving an invalid HTTP Message Body

401 UNAUTHORIZED

  • Authorization problems. E.g. wrong API key, etc.

403 FORBIDDEN

  • Properly authorized, but not allowed.

404 NOT FOUND

  • The resource does not exist (e.g. on Read or Update)

405 METHOD NOT ALLOWED

  • Use in situations that a given REST method is not allowed. E.g. a POST on a single resource, or a DELETE on the entire collection of resources.

409 CONFLICT

  • When an update fails, send "Conflict" to allow the client side to resolve the conflict themselves and retry.

500 INTERNAL SERVER ERROR

  • Internal error. This is the default code that is used for all unrecognized errors.

501 NOT IMPLEMENTED

  • Use for expected, but not yet implemented features.
Ariejan
A: 

As Ariejan said you should base your API in the HTTP codes already defined. If you want to send a error message the best way should be not use the HTTP message, but better include the message in the response body, JSON formatted.

juandebravo
A: 

422 Unprocessable Entity (see RFC 4918, Section 11.2)

Julian Reschke