如何公开REST API HAL格式分页

问题描述 投票:0回答:4

我应该如何使用 HAL 格式公开 REST API 的分页,我应该使用分页元数据将所有内容包装在另一个 HAL 格式的对象中还是?

REST API HAL 格式下有建议的分页格式吗?

更新

没有分页的示例

[
    {
        "Id": "SomeId",
        "Attribute": 5,
        "_links": {
            "User": { "href": "http://mywebapi/etc", "templated": true }
        },
        "_embedded": { "User": { "Id": "SomeId","_links": {},"_embedded": {}} }
    },
    {
        "Id": "SomeId",
        "Attribute": 5,
        "_links": {
            "User": { "href": "http://mywebapi/etc", "templated": true }
        },
        "_embedded": { "User": { "Id": "SomeId","_links": {},"_embedded": {}} }
    }
]

分页示例

{
    "_embedded": { 
    "items":
    [
        {
            "Id": "SomeId",
            "Attribute": 5,
            "_links": {
                "User": { "href": "http://mywebapi/etc", "templated": true }
            },
            "_embedded": { "User": { "Id": "SomeId","_links": {},"_embedded": {}} }
        },
        {
            "Id": "SomeId",
            "Attribute": 5,
            "_links": {
                "User": { "href": "http://mywebapi/etc", "templated": true }
            },
            "_embedded": { "User": { "Id": "SomeId","_links": {},"_embedded": {}} }
        }
    ]},
    "_links": {
        "next": "next link",
        "previous": "next link"
    },
    "_totalCount": "100"
}

这是否是一个好的做法?

json rest asp.net-web-api hateoas
4个回答
4
投票

顺便说一句,您在正确的 HAL RFC 中有一个示例

https://datatracker.ietf.org/doc/html/draft-kelly-json-hal-06#section-6

 "_links": {
   "self": { "href": "/orders" },
   "next": { "href": "/orders?page=2" },
   "find": { "href": "/orders{?id}", "templated": true }
 }

我不确定的是“_totalCount”...我也在弄清楚以 HAL 格式包含 TotalCount 属性的最佳方法是什么


2
投票

使用 rel="next" 和 rel="previous" 的链接


1
投票

_totalcount
可能会有问题。它是您返回的资源的固有属性吗?很可能不会。

如果您确实拥有它,那么您将被迫每次资源的每个页面提供此值。如果总集合非常大,则有必要将计数存储在某个地方以满足 API 的需要。在许多情况下,计数可能更难获得。例如,如果您基于提供延续令牌的其他服务来实现,则填充

_totalcount
将变得困难。如果你有 SQL 表,它可能相当容易获得,但它也是有代价的。

它对客户端或 UI 真的有价值吗?如果可能的话我会避免。


0
投票

如果有帮助,我们会这样做:

{
  "_items": [{
    ... // Your data elements go here
  }],
  "_paging": {
    "page": 0,
    "size": 10,
    "first": true,
    "last": false,
    "pages": 10,
    "items": 100
  },
  "_links": {
    "previous": {
      "href": ""
    },
    "next": {
      "href": ""
    },
    "first": {
      "href": ""
    },
    "last": {
      "href": ""
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.