是否存在从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!"
  }
}

当前回答

是的,出现了一些标准(尽管在标准定义上有些自由):

JSON API-JSON API还包括创建和更新资源,而不仅仅是响应。JSend-简单,可能是您已经在做的事情。OData JSON协议-非常复杂。哈尔-像OData,但目标是像HATEOAS。

还有JSON API描述格式:

大摇大摆JSON模式(swagger使用,但可以单独使用)JSON格式的WADL冲压,冲压HAL,因为理论上HATEOAS是自我描述的。

其他回答

我曾经遵循这个标准,在客户端层非常好、简单、干净。

通常,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) {
  ....
}

请注意我是如何提前打破厄运金字塔的。

对于后面的内容,除了包括HAL、JSend和JSON API的公认答案之外,我还将添加一些其他值得研究的规范:

JSON-LD,它是W3C推荐标准,规定了如何以JSON构建可互操作的Web服务Ion Hypermedia Type for REST,自称是“一种简单直观的基于JSON的REST超媒体类型”

我将此结构用于REST API:

{
  "success": false,
  "response": {
    "data": [],
    "pagination": {}
  },
  "errors": [
    {
      "code": 500,
      "message": "server 500 Error"
    }
  ]
}

我想事实上的标准还没有真正出现(可能永远不会)。但无论如何,我的看法是:

成功的请求:

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

失败的请求:

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

优势:成功和错误案例中的顶级元素相同

缺点:没有错误代码,但如果您愿意,您可以将状态更改为(成功或失败)代码,或者-您可以添加另一个名为“代码”的顶级项。

以下是instagram使用的json格式

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