是否存在从API构建JSON响应的标准或最佳实践?显然,每个应用程序的数据都是不同的,所以我不太关心,而是“响应样板”,如果你愿意的话。我的意思是:
成功的请求:
{
"success": true,
"payload": {
/* Application-specific data would go here. */
}
}
失败的请求:
{
"success": false,
"payload": {
/* Application-specific data would go here. */
},
"error": {
"code": 123,
"message": "An error occurred!"
}
}
他们对大型软件巨头(谷歌、脸书、推特、亚马逊等)的rest api响应格式没有达成一致,尽管上面的答案中提供了许多链接,一些人已经尝试将响应格式标准化。
由于API的需求可能不同,很难让每个人都加入并同意某种格式。如果您有数百万用户使用您的API,为什么要更改响应格式?
以下是我对谷歌、推特、亚马逊和互联网上一些帖子的回应格式的看法:
https://github.com/adnan-kamili/rest-api-response-format
交换文件:
https://github.com/adnan-kamili/swagger-sample-template
我曾经遵循这个标准,在客户端层非常好、简单、干净。
通常,HTTP状态为200,所以这是我在顶部使用的标准检查。我通常使用以下JSON
我还使用API的模板
dynamic response;
try {
// query and what not.
response.payload = new {
data = new {
pagination = new Pagination(),
customer = new Customer(),
notifications = 5
}
}
// again something here if we get here success has to be true
// I follow an exit first strategy, instead of building a pyramid
// of doom.
response.success = true;
}
catch(Exception exception){
response.success = false;
response.message = exception.GetStackTrace();
_logger.Fatal(exception, this.GetFacadeName())
}
return response;
{
"success": boolean,
"message": "some message",
"payload": {
"data" : []
"message": ""
... // put whatever you want to here.
}
}
在客户端层上,我将使用以下内容:
if(response.code != 200) {
// woops something went wrong.
return;
}
if(!response.success){
console.debug ( response.message );
return;
}
// if we are here then success has to be true.
if(response.payload) {
....
}
请注意我是如何提前打破厄运金字塔的。
为了值得,我采取了不同的做法。成功的调用只有JSON对象。我不需要更高级别的JSON对象,它包含一个指示true的成功字段和一个包含JSON对象的有效负载字段。我只需要返回一个适当的JSON对象,该对象带有一个200或任何在200范围内适合于标头中HTTP状态的值。
但是,如果有错误(400系列中的某些错误),我会返回一个格式良好的JSON错误对象。例如,如果客户端向用户发送电子邮件地址和电话号码,其中一个错误(即我无法将其插入基础数据库),我将返回如下内容:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
这里重要的一点是,“field”属性必须与无法验证的JSON字段完全匹配。这可以让客户确切地知道他们的请求出了什么问题。此外,“message”位于请求的区域设置中。如果“emailAddress”和“phoneNumber”都无效,那么“errors”数组将包含两者的条目。409(冲突)JSON响应体可能如下所示:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
有了HTTP状态代码和JSON,客户机就拥有了以确定性方式响应错误所需的一切,并且不会创建新的错误标准来尝试完全替换HTTP状态代码。注意,这些错误只发生在400个错误的范围内。对于200范围内的任何东西,我可以返回任何合适的东西。对我来说,它通常是一个类似于HAL的JSON对象,但这在这里并不重要。
我想添加的一件事是在“errors”数组条目或JSON对象本身的根中添加一个数字错误代码。但到目前为止,我们还不需要它。
他们对大型软件巨头(谷歌、脸书、推特、亚马逊等)的rest api响应格式没有达成一致,尽管上面的答案中提供了许多链接,一些人已经尝试将响应格式标准化。
由于API的需求可能不同,很难让每个人都加入并同意某种格式。如果您有数百万用户使用您的API,为什么要更改响应格式?
以下是我对谷歌、推特、亚马逊和互联网上一些帖子的回应格式的看法:
https://github.com/adnan-kamili/rest-api-response-format
交换文件:
https://github.com/adnan-kamili/swagger-sample-template
对于移动开发人员容易理解的web api的最佳响应。
这是“成功”响应
{
"code":"1",
"msg":"Successfull Transaction",
"value":"",
"data":{
"EmployeeName":"Admin",
"EmployeeID":1
}
}
这是“错误”响应
{
"code": "4",
"msg": "Invalid Username and Password",
"value": "",
"data": {}
}