REST API:创建自定义HTTP响应代码真的不是一个好习惯吗? [英] REST API: Is it a really bad practice to create custom HTTP response codes?

查看:155
本文介绍了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.

但是,并非所有情况都能完美满足.让Twitters保持冷静",该响应代码在请求有效时使用,只是因为发出了太多请求而没有处理该响应代码.

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天全站免登陆