问题
Is it a bad practice when writing a RESTful API to use custom HTTP response codes like:
- 417 - Password not provided
- 418 - Database error
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?
回答1:
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.
回答2:
The problems in using your own codes are:
- The code you choose may get officially assigned to something completely different, and that could break your API in the future. (e.g. compare a 306 with a 301)
- Intermediaries don't know what your code means, so cannot optimise anything. The internet works so well because it is a distributed system, not an end-to-end system.
- There are generic responses for each category, x00, which should be used if nothing better exists.
- You can send your own more specific error code in either the response body or (not as good) a response header. There should be no need to make up your own codes. If you have truly found something that would benefit the rest of the internet and no-one else has thought of until now, you can always submit an Internet Draft to the IETF (this is fairly easy to do).
I would not hold up Twitter as a shining example of good internet practice, though. :)
来源:https://stackoverflow.com/questions/25546848/rest-api-is-it-a-really-bad-practice-to-create-custom-http-response-codes