Google json 风格指南:如何发送单项响应?

Google json style guide: How to send single item response?

规范中有一个 items 节点,表示它用于项目数组,如分页项目、youtube 视频列表

如果我对单个项目有 GET 请求,应该如何格式化响应?

数组中的一项? 项目:[项目]

https://google.github.io/styleguide/jsoncstyleguide.xml

您不需要 items 字段来显示单个项目。如果你确定你的 API 总是去 return 单个对象,你可以 return 它作为 data 本身。

{
  "data": {
    "kind": "user",
    "fields": "author,id",
    "id": "bart",
    "author": "Bart"
  }
}

data.kind data.fields data.etag data.id data.lang data.updated data.deleted等字段仍然可以在这里使用。

片段来源 docs

我认为@tanmay_vijay 的回答不够正确或不够细致,因为在文档的 YouTube 示例中,单个项目响应似乎在数组中。

{
  "apiVersion": "2.0",
  "data": {
    "updated": "2010-02-04T19:29:54.001Z",
    "totalItems": 6741,
    "startIndex": 1,
    "itemsPerPage": 1,
    "items": [
      {
        "id": "BGODurRfVv4",
        "uploaded": "2009-11-17T20:10:06.000Z",
        "updated": "2010-02-04T06:25:57.000Z",
        "uploader": "docchat",
        "category": "Animals",
        "title": "From service dog to SURFice dog",
        "description": "Surf dog Ricochets inspirational video ...",
        "tags": [
          "Surf dog",
          "dog surfing",
          "dog",
          "golden retriever",
        ],
        "thumbnail": {
          "default": "https://i.ytimg.com/vi/BGODurRfVv4/default.jpg",
          "hqDefault": "https://i.ytimg.com/vi/BGODurRfVv4/hqdefault.jpg"
        },
        "player": {
          "default": "https://www.youtube.com/watch?v=BGODurRfVv4&feature=youtube_gdata",
          "mobile": "https://m.youtube.com/details?v=BGODurRfVv4"
        },
        "content": {
          "1": "rtsp://v5.cache6.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
          "5": "https://www.youtube.com/v/BGODurRfVv4?f=videos&app=youtube_gdata",
          "6": "rtsp://v7.cache7.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
        },
        "duration": 315,
        "rating": 4.96,
        "ratingCount": 2043,
        "viewCount": 1781691,
        "favoriteCount": 3363,
        "commentCount": 1007,
        "commentsAllowed": true
      }
    ]
  }
}

然而,这可能取决于请求的目标资源。这就是竞争 JSONAPI 标准中的方式。

来自 JSONAPI 标准:

A logical collection of resources MUST be represented as an array, even if it only contains one item or is empty.