[英]REST API error return, include HTTP status code or not
I'm working on an restful API back end, and we only use json as content type. 我正在开发一个宁静的API后端,并且我们仅使用json作为内容类型。 And There are two ways of performing error response as I know: 据我所知,有两种执行错误响应的方法:
I want to know which one is more idiom for a restful service? 我想知道哪一种更适合休闲服务?
You need to use both. 您需要同时使用两者。
HTTP Status : Use this to process the status of the request. HTTP状态 :使用它来处理请求的状态。 For example, if you query a DB and you find no entries, you'll still return 200. If the user is not authorized, 403, if number of SQL connections exceed, 500, and so on. 例如,如果查询数据库,但没有找到条目,则仍将返回200。如果未授权用户,则返回403,如果SQL连接数超过500,以此类推。
API Status : If the DB request succeed and you find no entries, include a custom field in your json {status: NO_ENTRIES }
or { status: DEPRECATED_API }
. API状态 :如果数据库请求成功,但您找不到任何条目,请在json {status: NO_ENTRIES }
或{ status: DEPRECATED_API }
包含一个自定义字段。 In these cases, the response code will still be 200. 在这些情况下,响应代码仍为200。
Generally speaking, I would not advocate for always returning a 200. There are failure scenarios that match commonly accepted status codes. 一般来说,我不主张总是返回200。有些失败情况与普遍接受的状态代码相匹配。 Above, someone mentioned 403, which you deliver when access is denied. 上面提到了有人403,当访问被拒绝时您将提供它。 And 500 is typically issued by the web/app server when things really go south. 当事情真的很严重时,通常由Web /应用程序服务器发出500。 And 404 if either a record is not found for a resource. 404,如果找不到资源的任何记录。
So, I do advocate for: 因此,我主张:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.