是否存在从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!"
}
}
建议的基本框架看起来不错,但定义的错误对象太有限。人们通常不能用一个值来表达问题,而是需要一系列问题和原因。
我做了一点研究,发现返回错误(异常)最常见的格式是以下形式的结构:
{
"success": false,
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
这是OASIS数据标准OASIS OData提出的格式,似乎是最标准的选项,但目前任何标准的采用率似乎都不高。此格式与JSON-RPC规范一致。
您可以在以下位置找到实现此功能的完整开源库:Mendocino JSON Utilities。该库支持JSON对象以及异常。
详细信息在我关于JSON REST API中的错误处理的博客文章中讨论
我曾经遵循这个标准,在客户端层非常好、简单、干净。
通常,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) {
....
}
请注意我是如何提前打破厄运金字塔的。
对于移动开发人员容易理解的web api的最佳响应。
这是“成功”响应
{
"code":"1",
"msg":"Successfull Transaction",
"value":"",
"data":{
"EmployeeName":"Admin",
"EmployeeID":1
}
}
这是“错误”响应
{
"code": "4",
"msg": "Invalid Username and Password",
"value": "",
"data": {}
}
有点晚了,但这是我对HTTP错误响应的看法,我发送代码(通过状态)、通用消息和详细信息(如果我想提供特定端点的详细信息,有些是不言自明的,因此不需要详细信息,但它可以是自定义消息,甚至可以是完整的堆栈跟踪,具体取决于用例)。为了成功,数据属性中的格式、代码、消息和任何数据都是类似的。
ExpressJS响应示例:
// Error
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: `missing ${missingParam}`,
}
});
// or
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: 'expected: {prop1, prop2, prop3',
}
});
// Success
res
.status(200)
.json({
message: 'password updated',
data: {member: { username }}, // [] ...
});