[英]Handling REST API server response
I've been working with REST API CodeIgniter for more than a year and usually when I want to return any response I will return 200
for all kind of request.我已经使用 REST API CodeIgniter 一年多了,通常当我想返回任何响应时,我会为所有类型的请求返回
200
。 I know that there are status code provided for all response but I am actually quite wondering, is it wrong if I use 200
for all response?我知道所有响应都提供了状态代码,但我实际上很想知道,如果我对所有响应都使用
200
是错误的吗? And determine the data status with true
and false
.并用
true
和false
确定数据状态。
Here is the sample code that I always use.这是我一直使用的示例代码。 Let's say to check whether the user is exist or not.
假设要检查用户是否存在。
CodeIgniter REST API CodeIgniter REST API
$user = [ 'id' => 1, 'name' => 'John Doe' ];
$this->response([
'status' => !empty($user) ? true : false,
'user' => $user
], REST_Controller::HTTP_OK);
React Native反应本机
try {
const res = await axios.get('https://www.example.com/retrieve-user?user_id=3');
if (res.status == 200){
if(res.data.status == true){
// user found
} else {
// user not found
}
} else {
alert('Internal server error.')
}
} catch (err) {
console.error(err);
}
Based on the example, I am actually depending on the status code 200
to determine if there is an error in the server (code error, invalid request, etc).基于这个例子,我其实是根据状态码
200
来判断服务器是否有错误(代码错误、无效请求等)。
So my question is, is it okay to stick with this method?所以我的问题是,坚持这种方法可以吗?
Given your API, yes handling code 200
seems enough as your API might not return any other HttpCode.鉴于您的 API,是处理代码
200
似乎就足够了,因为您的 API 可能不会返回任何其他 HttpCode。
Given a bigger API (even simple), no .给定一个更大的 API(甚至是简单的),没有.
Your API might return a 204
/ 404
if no user if found with given id.如果没有找到具有给定 id 的用户,您的 API 可能会返回
204
/ 404
。
Your API might return a 503
if your API is under deployment (and unavailable) or under maintenance, and you may retry 30 seconds later.如果您的 API 正在部署(且不可用)或维护中,您的 API 可能会返回
503
,您可以在 30 秒后重试。
Your API might reject request if a given header is missing (Content-Type ...) and return a 400
...如果缺少给定的标头(Content-Type ...),您的 API 可能会拒绝请求并返回
400
...
EDIT 1 :编辑 1:
if (res.status == 200){
// user found
} else if (res.status == 204) {
// user not found
} else {
alert('An error occured')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.