php - 如果无法执行操作,API 应该返回什么?

标签 php json api mobile backend

我正在用 PHP 为移动应用程序编写 API。其中一个端点 create-user.php 应该用于向 User 表添加新记录。如果应用程序试图创建副本怎么办?我可以捕获它并返回一条错误消息(顺便说一句?)。问题是,我是否也应该返回一个结构如下的 JSON:

{
   "status": "The email already exists"
}

...向客户提供有关问题所在的更多信息?还是我应该只使用错误代码,仅此而已?

最佳答案

返回http状态422和错误信息

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions. page statistics

具体来说:

422 status code feels much more appropriate. The server understands what you're trying to do; and it understands the data that you're submitting; it simply won't let that data be processed.

阅读更多来自 Ben Nadel 的文章:http://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm

此外,Laravel 框架在其 Request Form 类中还使用“失败规则”(例如电子邮件已存在)的 http 状态 422。看到这个:http://laravel.com/docs/master/validation

关于php - 如果无法执行操作,API 应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32052760/

相关文章:

python - 将附加数据添加到 django Rest Framework View 集响应

javascript - 在 angularjs 中使用 $http 将 json 文件显示到 View

php - 如何使用 PHP/MySQL 建立主题标签之间的关系?

php - 使用 PHP 生成串行

PHP如何使用数组中的变量

php - 删除 PHP 多维数组中的父项

java - Grooveshark api 总是返回 "Method not found"消息

php - bind_param 数字参数不等于变量

javascript - 我如何处理 jQuery.Ajax 中的时间响应(数据类型 : JSON)?

amazon-web-services - 有没有办法通过 API Gateway 执行粘合作业?