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

当前回答

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

这是“成功”响应

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

这是“错误”响应

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

其他回答

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

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

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

建议的基本框架看起来不错,但定义的错误对象太有限。人们通常不能用一个值来表达问题,而是需要一系列问题和原因。

我做了一点研究,发现返回错误(异常)最常见的格式是以下形式的结构:

{
   "success": false,
   "error": {
      "code": "400",
      "message": "main error message here",
      "target": "approx what the error came from",
      "details": [
         {
            "code": "23-098a",
            "message": "Disk drive has frozen up again.  It needs to be replaced",
            "target": "not sure what the target is"
         }
      ],
      "innererror": {
         "trace": [ ... ],
         "context": [ ... ]
      }
   }
}

这是OASIS数据标准OASIS OData提出的格式,似乎是最标准的选项,但目前任何标准的采用率似乎都不高。此格式与JSON-RPC规范一致。

您可以在以下位置找到实现此功能的完整开源库:Mendocino JSON Utilities。该库支持JSON对象以及异常。

详细信息在我关于JSON REST API中的错误处理的博客文章中讨论

有点晚了,但这是我对HTTP错误响应的看法,我发送代码(通过状态)、通用消息和详细信息(如果我想提供特定端点的详细信息,有些是不言自明的,因此不需要详细信息,但它可以是自定义消息,甚至可以是完整的堆栈跟踪,具体取决于用例)。为了成功,数据属性中的格式、代码、消息和任何数据都是类似的。

ExpressJS响应示例:

// Error

    res
      .status(422)
      .json({
        error: {
          message: 'missing parameters',
          details: `missing ${missingParam}`,
        }
      });
        
    // or
        
    res
      .status(422)
      .json({
        error: {
          message: 'missing parameters',
          details: 'expected: {prop1, prop2, prop3',
        }
      });

 // Success

    res
      .status(200)
      .json({
         message: 'password updated',
         data: {member: { username }}, // [] ...
      });

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

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

JSON的关键在于它是完全动态和灵活的。你可以随心所欲地使用它,因为它只是一组序列化的JavaScript对象和数组,植根于一个节点。

rootnode的类型取决于您,它包含的内容取决于您、是否随响应一起发送元数据取决于您以及是否将mime类型设置为application/json或将其保留为text/plain取决于您(只要您知道如何处理边缘情况)。

构建您喜欢的轻量级模式。就我个人而言,我发现分析跟踪、mp3/ogg服务、图片库服务、在线游戏的短信和网络包、博客帖子和博客评论在发送内容、接收内容以及如何消费方面都有着非常不同的要求。

所以,在完成所有这些工作时,我最不想做的就是让每一个都符合相同的样板标准,该标准基于XML2.0或类似的标准。

也就是说,使用对你有意义且经过深思熟虑的模式有很多值得说的地方。只需阅读一些API响应,注意你喜欢的,批评你不喜欢的,写下这些批评,并理解它们为什么会让你感到不舒服,然后思考如何将你学到的东西应用到你需要的东西上。