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

大兔子大兔子 提交于 2019-12-05 18:07:00

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.

The problems in using your own codes are:

  1. 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)
  2. 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.
  3. There are generic responses for each category, x00, which should be used if nothing better exists.
  4. 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. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!