是否存在从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!"
}
}
我曾经遵循这个标准,在客户端层非常好、简单、干净。
通常,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) {
....
}
请注意我是如何提前打破厄运金字塔的。
他们对大型软件巨头(谷歌、脸书、推特、亚马逊等)的rest api响应格式没有达成一致,尽管上面的答案中提供了许多链接,一些人已经尝试将响应格式标准化。
由于API的需求可能不同,很难让每个人都加入并同意某种格式。如果您有数百万用户使用您的API,为什么要更改响应格式?
以下是我对谷歌、推特、亚马逊和互联网上一些帖子的回应格式的看法:
https://github.com/adnan-kamili/rest-api-response-format
交换文件:
https://github.com/adnan-kamili/swagger-sample-template