Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API: Is it a really bad practice to create custom HTTP response codes?

Is it a bad practice when writing a RESTful API to use custom HTTP response codes like:

  • 417 - Password not provided
  • 418 - Database error

API custom response codes

I see there is a list of standard HTTP response codes. However, from looking at Twitter's API, it appears Twitter tries to return standard HTTP response codes when available but their own error codes when they cannot align the error with a standard HTTP response (correct me if I am wrong).

What is the best practice for response codes (especially for errors) while creating a RESTful API? Any comments on the practice which Twitter chose to use?

like image 245
Placeholder Avatar asked Aug 28 '14 10:08

Placeholder


People also ask

Can you make your own HTTP status code?

Yes, as long as you respect the class -- that is, 2xx for success, 4xx for Client error, etc. So you can return custom 4XX error codes (preferably those that are unassigned) for your own application's error conditions.

Should REST API always return 200?

However, they told me specifiying status code like 400, 404, 300, is part of RESTful API, and returning always 200 is the right status code because the server responded and it is alive. APIs, always have to return 200 except 500. Because when the server dies, it can't return anything.

What is the best HTTP response code for successful post request?

200 OK or 201 Created are the best choice for a successful POST request.


1 Answers

Yes, yes it is bad practice... mostly.

One of the tenets of REST is that you work with the underlying protocols, as such HTTP has already defined a good set of response codes.

However, not every situation is catered for perfectly. Take Twitters 'arrest your calm', that response code is used when the request was valid, it simply is not being handled due to too many request being made.

I don't see another response code that quite matches that. The other two options are to either lie, and tell the user the request failed for some other response or give a generic 400 'you did something bad' (then in the body give a more detailed explanation).

I would favour using the generic X00 codes, and use headers or the body to add more detail about what actually went wrong. This at least conforms better to standards and less brittle.

Note though, it is terrible to take an existing error code, and repurpose it. 404 should always be used only for 'not found' errors. Don't start using it because the user can't make that request at this time of day.

like image 118
thecoshman Avatar answered Oct 08 '22 07:10

thecoshman