REST API:创建自定义 HTTP 响应代码是一种非常糟糕的做法吗? [英] REST API: Is it a really bad practice to create custom HTTP response codes?

查看:25
本文介绍了REST API:创建自定义 HTTP 响应代码是一种非常糟糕的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写 RESTful API 以使用自定义 HTTP 响应代码(例如:

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

  • 417 - 未提供密码
  • 418 - 数据库错误

我看到有一个 标准 HTTP 响应代码的列表.但是,从 Twitter 的 API 来看,Twitter 似乎试图返回标准 HTTP可用时使用响应代码,但在无法将错误与标准 HTTP 响应对齐时使用自己的错误代码(如果我错了,请纠正我).

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).

创建 RESTful API 时响应代码(尤其是错误)的最佳实践是什么?对 Twitter 选择使用的做法有何评论?

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?

推荐答案

是的,是的,这是不好的做法......主要是.

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

REST 的一个原则是您使用底层协议,因为 HTTP 已经定义了一组很好的响应代码.

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.

但是,并非每种情况都能完美满足.以 Twitter 为例,请保持冷静",当请求有效时使用响应代码,它只是由于请求过多而没有被处理.

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.

我没有看到与此完全匹配的另一个响应代码.另外两个选项是撒谎,并告诉用户请求因其他响应而失败,或者给出一个通用的 400你做错了什么"(然后在正文中给出更详细的解释).

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).

我更喜欢使用通用 X00 代码,并使用标题或正文添加有关实际出错的更多详细信息.这至少更符合标准且不易碎.

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.

但是请注意,使用现有的错误代码并重新利用它是很糟糕的.404 应始终仅用于未找到"错误.不要开始使用它,因为用户无法在一天中的这个时间提出该请求.

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.

这篇关于REST API:创建自定义 HTTP 响应代码是一种非常糟糕的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆