Standard JSON API response format?

Do standards or best practices exist for structuring JSON responses from an API? 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!"
  }
}

Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:

  • JSON API - JSON API covers creating and updating resources as well, not just responses.
  • JSend - Simple and probably what you are already doing.
  • OData JSON Protocol - Very complicated.
  • HAL - Like OData but aiming to be HATEOAS like.
  • There are also JSON API description formats:

  • Swagger
  • JSON Schema (used by swagger but you could use it stand alone)
  • WADL in JSON
  • RAML
  • HAL because HATEOAS in theory is self describing.

  • Google JSON guide

    Success response return data

    {
      "data": {
        "id": 1001,
        "name": "Wing"
      }
    }
    

    Error response return error

    {
      "error": {
        "code": 404,
        "message": "ID not found"
      }
    }
    

    and if your client is JS, you can using if ("error" in response) {} to check if there is error.


    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 status to be a (success or failure) code, -or- you can add another top level item named "code".

    链接地址: http://www.djcxy.com/p/1312.html

    上一篇: 将不可解析的cruft添加到ASP.NET MVC JsonResult

    下一篇: 标准的JSON API响应格式?