php - 关于API 使用 HTTP 状态码还是全部返回 200
我想大声告诉你
我想大声告诉你 2017-05-16 13:03:19
0
6
829

现在的项目api想用restful风格,然后目前的api接口返回规范:所有成功接口返回{status:200,msg:'',data:{}},出错接口返回{status:403,msg:'',data:{}},也就是只有200和403两种状态,我感觉不太对劲,搜了下网上的

    200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。
    201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。
    202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)
    204 NO CONTENT - [DELETE]:用户删除数据成功。
    400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。
    401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。
    403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。
    404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。
    406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。
    410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。
    422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。
    500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。

我是否是要按照这样的规范根据不同的情况去返回状态码?比如get请求成功返回200,post请求成功返回201?而不是只要成功就返回200?话说这些状态码真的是写在返回值里吗?不是应该http协议里自动判定的吗?或者在返回的header里修改?这里很迷糊,希望大神解惑!

我想大声告诉你
我想大声告诉你

reply all(6)
巴扎黑

There are two methods
1.status_code is all 200, the response body is as follows:
成功

{
  errcode: 0,
  errmsg: null,
  data: obj // 数据主体
}

失败

{
  errcode: 1, // 具体错误代码
  errmsg: '账号错误',
}

2. Process according to different status_code (recommended)
成功(2xx) and return the data directly without additional packaging

[]// 或者{}

失败(4xx,5xx), return errcode and errmsg

{
  errcode: 1,
  errmsg: '账号或密码错误',
}
Ty80

{status:200,msg:'',data:{}} This should be the return result written by you in the API. For example, the servlet returns a json string containing these 3 fields. In other words, the front end can only read this information when your api returns successfully. If the request fails and cannot be read, you can try requesting a wrong URL from the front end

某草草

In fact, if it is standardized, it should be returned like this
header('HTTP/1.0 401 Unauthorized');
header('HTTP/1.0 403 Forbidden');

However, in actual situations, many people will not be so standardized.
Even GET requests and POST requests are being mixed, so how can we talk about standards?

刘奇

Originally, it should be done according to the regulations, but domestic telecom operators may hijack the redirect. For example, if you return 404, the operator may redirect you to their own navigation website, which would be embarrassing.

过去多啦不再A梦

The data returned by your interface and the http response are two different things

The code returned by the interface is predetermined. You can set it however you want.

The information you are checking is the status code of the http response and has nothing to do with the return from your interface

習慣沉默

Business error code 4xx
Success 200 - 204
System error 5xx

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!