是否存在从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) {
....
}
请注意我是如何提前打破厄运金字塔的。
我想事实上的标准还没有真正出现(可能永远不会)。但无论如何,我的看法是:
成功的请求:
{
"status": "success",
"data": {
/* Application-specific data would go here. */
},
"message": null /* Or optional success message */
}
失败的请求:
{
"status": "error",
"data": null, /* or optional error payload */
"message": "Error xyz has occurred"
}
优势:成功和错误案例中的顶级元素相同
缺点:没有错误代码,但如果您愿意,您可以将状态更改为(成功或失败)代码,或者-您可以添加另一个名为“代码”的顶级项。