标准JSON API响应格式?

彭海阳
2023-12-01

本文翻译自: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-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed. 就个人而言,我发现对于在线游戏,分析跟踪和mp3 / ogg服务,图像库服务,文本消息和网络数据包以及博客帖子和博客评论对内容有不同的要求发送,接收的内容以及如何使用它们。

So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch. 因此,在执行所有这些操作时,我最后想要做的就是尝试使每个标准都符合基于XML2.0或类似标准的同一样板标准。

That said, there's a lot to be said for using schemas which make sense to you and are well thought out. 就是说,使用对有意义并且经过深思熟虑的模式有很多话要说。
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need. 只需阅读一些API响应,记下您喜欢的东西,批评您不喜欢的东西,写下那些批评并理解为什么它们会以错误的方式摩擦您,然后考虑如何将您学到的知识运用到您的需求中。


#3楼

Assuming you question is about REST webservices design and more precisely concerning success/error. 假设您的问题与REST Web服务设计有关,更确切地说与成功/错误有关。

I think there are 3 different types of design. 我认为有3种不同类型的设计。

  1. Use only HTTP Status code to indicate if there was an error and try to limit yourself to the standard ones (usually it should suffice). 使用HTTP状态代码来指示是否存在错误,并尝试将自己限制为标准错误(通常应该足够)。

    • Pros: It is a standard independent of your api. 优点:这是独立于您的api的标准。
    • Cons: Less information on what really happened. 缺点:关于实际发生情况的信息较少。
  2. Use HTTP Status + json body (even if it is an error). 使用HTTP状态+ json正文 (即使它是错误的)。 Define a uniform structure for errors (ex: code, message, reason, type, etc) and use it for errors, if it is a success then just return the expected json response. 为错误定义统一的结构(例如:代码,消息,原因,类型等),并将其用于错误,如果成功,则只需返回预期的json响应。

    • Pros: Still standard as you use the existing HTTP status codes and you return a json describing the error (you provide more information on what happened). 优点:使用现有的HTTP状态代码并返回描述错误的json(仍提供有关发生的情况的更多信息)时,仍然是标准的。
    • Cons: The output json will vary depending if it is a error or success. 缺点:输出json会因错误或成功而有所不同。
  3. Forget the http status (ex: always status 200), always use json and add at the root of the response a boolean responseValid and a error object (code,message,etc) that will be populated if it is an error otherwise the other fields (success) are populated. 忘记http状态 (例如:始终为200),始终使用json并在响应的根添加一个布尔responseValid和一个错误对象(代码,消息等),如果错误则将填充该对象,否则其他字段(成功)已填充。

    • Pros: The client deals only with the body of the response that is a json string and ignores the status(?). 优点:客户端仅处理响应的主体(是json字符串),并且忽略status(?)。

    • Cons: The less standard. 缺点:不太标准。

It's up to you to choose :) 由您选择:)

Depending on the API I would choose 2 or 3 (I prefer 2 for json rest apis). 根据API,我会选择2或3(对于JSON rest api,我更喜欢2)。 Another thing I have experienced in designing REST Api is the importance of documentation for each resource (url): the parameters, the body, the response, the headers etc + examples. 在设计REST Api时,我经历的另一件事是每种资源(url)的文档重要性:参数,正文,响应,标头等以及示例。

I would also recommend you to use jersey (jax-rs implementation) + genson (java/json databinding library). 我还建议您使用jersey(jax-rs实现)+ genson (java / json数据绑定库)。 You only have to drop genson + jersey in your classpath and json is automatically supported. 您只需要在类路径中放入genson + jersey,即可自动支持json。

EDIT: 编辑:

  • Solution 2 is the hardest to implement but the advantage is that you can nicely handle exceptions and not only business errors, initial effort is more important but you win on the long term. 解决方案2是最难实现的,但优点是您可以很好地处理异常,不仅可以处理业务错误,初始工作更为重要,但从长远来看却可以取胜。

  • Solution 3 is the easy to implement on both, server side and client but it's not so nice as you will have to encapsulate the objects you want to return in a response object containing also the responseValid + error. 解决方案3在服务器端和客户端上都易于实现,但效果不佳,因为您必须将要返回的对象封装在还包含responseValid +错误的响应对象中。


#4楼

I guess a defacto standard has not really emerged (and may never). 我想事实上的标准并没有真正出现(也许永远不会)。 But regardless, here is my take: 但是无论如何,这是我的看法:

Successful request: 成功的请求:

{
  "status": "success",
  "data": {
    /* Application-specific data would go here. */
  },
  "message": null /* Or optional success message */
}

Failed request: 请求失败:

{
  "status": "error",
  "data": null, /* or optional error payload */
  "message": "Error xyz has occurred"
}

Advantage: Same top-level elements in both success and error cases 优势:成功案例和错误案例中的顶级元素相同

Disadvantage: No error code, but if you want, you can either change the status to be a (success or failure) code, -or- you can add another top-level item named "code". 缺点:没有错误代码,但是如果需要,可以将状态更改为(成功或失败)代码,或者-可以添加另一个名为“代码”的顶级项。


#5楼

Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged: 是的,已经出现了一些标准(尽管对标准的定义有一些自由):

  1. JSON API - JSON API covers creating and updating resources as well, not just responses. JSON API -JSON API还涵盖创建和更新资源,而不仅仅是响应。
  2. JSend - Simple and probably what you are already doing. JSend-简单,可能正在做的事情。
  3. OData JSON Protocol - Very complicated. OData JSON协议 -非常复杂。
  4. HAL - Like OData but aiming to be HATEOAS like. HAL - OData的一样,但目标是成为HATEOAS等。

There are also JSON API description formats: 还有JSON API描述格式:


#6楼

Following is the json format instagram is using 以下是Instagram使用的json格式

{
    "meta": {
         "error_type": "OAuthException",
         "code": 400,
         "error_message": "..."
    }
    "data": {
         ...
    },
    "pagination": {
         "next_url": "...",
         "next_max_id": "13872296"
    }
}
 类似资料: