本文翻译自:Standard JSON API response format?
Do standards or best practices exist for structuring JSON responses from an API? 是否存在用于构造来自API的JSON响应的标准或最佳实践? Obviously, every application's data is different, so that much I'm not concerned with, but rather the "response boilerplate", if you will. 显然,每个应用程序的数据都是不同的,因此您不必担心很多,而是“响应样板”。 An example of what I mean: 我的意思的例子:
Successful request: 成功的请求:
{
"success": true,
"payload": {
/* Application-specific data would go here. */
}
}
Failed request: 请求失败:
{
"success": false,
"payload": {
/* Application-specific data would go here. */
},
"error": {
"code": 123,
"message": "An error occurred!"
}
}
#1楼
参考:https://stackoom.com/question/rjWc/标准JSON-API响应格式
#2楼
The point of JSON is that it is completely dynamic and flexible. JSON的要点是它是完全动态和灵活的。 Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node. 将其弯曲成您想要的任何方式,因为它只是一组序列化的JavaScript对象和数组,它们植根于单个节点。
What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json
or leave it as text/plain
is up to you (as long as you know how to handle the edge cases). rootnode的类型取决于您,它包含的内容取决于您,是否随响应发送元数据取决于您,是否将mime-type设置为application/json
还是将其保留为text/plain
取决于您(只要您知道如何处理边缘情况)。
Build a lightweight schema that you like. 构建您喜欢的轻量级架构。
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-me