Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should an API return if the operation can't be performed?

I am writing an API in PHP for a mobile app. One of the endpoints, create-user.php, should be used to add new records to the User table. What if the application is trying to create a duplicate? I can catch this and return an error message (which, by the way?). The question is, should I also return a JSON with a structure like:

{
   "status": "The email already exists"
}

...to give the client more information about what went wrong? Or should I just use the error codes and that's it?

like image 572
Edgar Derby Avatar asked Sep 06 '25 03:09

Edgar Derby


1 Answers

Return the http status 422 and an error message

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. page statistics

Concretely:

422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

Read more from Ben Nadel: http://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

Further, the Laravel framework uses in it's Request Form class also the http status 422 by 'failed rules' (e.g. email already exists). See this: http://laravel.com/docs/master/validation

like image 151
schellingerht Avatar answered Sep 07 '25 22:09

schellingerht