是否存在从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) {
....
}
请注意我是如何提前打破厄运金字塔的。
有点晚了,但这是我对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 }}, // [] ...
});
JSON的关键在于它是完全动态和灵活的。你可以随心所欲地使用它,因为它只是一组序列化的JavaScript对象和数组,植根于一个节点。
rootnode的类型取决于您,它包含的内容取决于您、是否随响应一起发送元数据取决于您以及是否将mime类型设置为application/json或将其保留为text/plain取决于您(只要您知道如何处理边缘情况)。
构建您喜欢的轻量级模式。就我个人而言,我发现分析跟踪、mp3/ogg服务、图片库服务、在线游戏的短信和网络包、博客帖子和博客评论在发送内容、接收内容以及如何消费方面都有着非常不同的要求。
所以,在完成所有这些工作时,我最不想做的就是让每一个都符合相同的样板标准,该标准基于XML2.0或类似的标准。
也就是说,使用对你有意义且经过深思熟虑的模式有很多值得说的地方。只需阅读一些API响应,注意你喜欢的,批评你不喜欢的,写下这些批评,并理解它们为什么会让你感到不舒服,然后思考如何将你学到的东西应用到你需要的东西上。