rest - 如何以 REST 方式对响应进行分组以便于客户端使用

标签 rest restful-architecture restful-url

假设我有两个表,Book 和 Author,其中每本书都有一个作者的外键。 /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'}
    ]
  }
]

最佳答案

我希望有一个作者资源,其中包含他们所写的每本书的链接或他们所写的所有书籍的集合的链接。无论哪种情况,您的 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"
        },
    ]
}

顺便说一句,在真实的系统中,一本书应该能够有多个作者。

关于rest - 如何以 REST 方式对响应进行分组以便于客户端使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36164344/

相关文章:

java - 使用 spring Restful api 对 url 进行编码?

python - 如何在 Flask API 路由系统中定义基本路由

django - 客户端 JS + Django Rest 框架

Spring MVC 3.1 - REST Web 服务版本控制

php - YII2 安静的奇怪行为

api - 现有资源的 Restful 链接

java - 如何在rest API中使用zip4j下载压缩文件?

java - 具有多个@RequestParam 的 Spring Boot API 调用

web-services - 什么时候不使用 REST API?

validation - 通过 REST API 验证/更改密码