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

当前回答

我将此结构用于REST API:

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

其他回答

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

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

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

对于移动开发人员容易理解的web api的最佳响应。

这是“成功”响应

{  
   "code":"1",
   "msg":"Successfull Transaction",
   "value":"",
   "data":{  
      "EmployeeName":"Admin",
      "EmployeeID":1
   }
}

这是“错误”响应

{
    "code": "4",
    "msg": "Invalid Username and Password",
    "value": "",
    "data": {}
}

Google JSON指南

成功响应返回数据

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

错误响应返回错误

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

如果您的客户端是JS,则可以使用if(响应中的“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"
}

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

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

RFC 7807:HTTP API的问题细节是目前最接近官方标准的内容。