【问题标题】:How to RESTfully group a response for easier client consumption如何对响应进行 RESTful 分组以更轻松地使用客户端
【发布时间】:2016-03-22 20:17:33
【问题描述】:

假设我有两个表,书和作者,其中每本书都有一个作者的外键。 /books/ 端点返回存储在系统中的所有书籍的列表。现在假设客户端将使用此列表,并按作者对其进行分组。让服务器返回按作者嵌套和分组的数据以使客户端不需要返回是否是 RESTful?是否有请求响应分组方法的标准? (可能类似于/books/?groupby=author)

例如:

// flat
[
  {'title': 'Harry Potter', 'author': 'JK Rowling'},
  {'title': 'Harry Potter 2', 'author': 'JK Rowling'},
  {'title': 'Harry Potter 3', 'author': 'JK Rowling'},
  {'title': 'Lord of the Rings', 'author': 'J. R. R. Tolkien'},
]

对

// nested
[
  {'author': 'JK Rowling', books: 
    [
      {'title': 'Harry Potter'},
      {'title': 'Harry Potter 2'},
      {'title': 'Harry Potter 3'},
    ]
  },
  {'author': 'J. R. R. Tolkien', books:
    [
      {'title': 'Lord of the Rings'}
    ]
  }
]

【问题讨论】:

  • 我认为这种操作没有标准。分组可以由客户完成,也可以作为您提到的另一种方法提供。
  • 看看 JSON 指针。

标签: rest restful-architecture restful-url


【解决方案1】:

我希望有一个作者资源,其中包含指向他们撰写的每本书的链接或指向他们撰写的所有书籍的集合的链接。在任何一种情况下,您的 API 都可以支持查询参数“?embed=books”,它会在返回的 JSON 中填充书籍。

GET /authors/23
{
    "name": "JK Rowling",
    "_links": [
        "books": [
            "/books/4",
            "/books/532"
        ], ...
    ]
}

GET /authors/23?embed=books
{
    "name": "JK Rowling",
    "books": [
        {
            "title": "Harry Potter",
            "author": "/authors/23"
        },
        {
            "title": "Harry Potter 2",
            "author": "/authors/23"
        },
    ]
}

顺便说一句,在实际系统中,一本书应该可以有多个作者。

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    相关资源
    最近更新 更多