是否包含其他API

时间:2018-06-25 14:48:35

标签: rest api

我有一个问题,我很难清楚地确定正确答案。

我的API有一个进行分页的端点。因此,在响应中,我必须将查询影响的总行数返回给客户端。实际记录数。

我已经读过,我应该像传递我想要的元数据那样将其包裹起来,但是我也读过,用元数据影响身体是不行的,未来要返回正文上只有非元数据,这意味着它必须位于响应标头上。

O'reilly If the information you are conveying through a custom HTTP header is important for the correct interpretation of the request or response, include that information in the body of the request or response or the URI used for the request. Avoid custom headers for such usages.

所以,我的问题是,解决该问题的正确方法是什么?我应该在响应标头中传递行数还是将其放在消息正文中。

非常感谢您。

1 个答案:

答案 0 :(得分:0)

对于分页,可以在响应有效载荷中使用信封:

{
  "data": [...],
  "paging": {
    "first": "http://api.example.com/foo?page=1&size=10",
    "previous": "http://api.example.com/foo?page=2&size=10"
    "next": "http://api.example.com/foo?page=4&size=10"
    "last": "http://api.example.com/foo?page=5&size=10"
  }
}

similar approach中描述了RFC 5005:结果的每一页都是一个单独的资源,其中包含指向结果的上一页和下一页的超链接


您还可以使用Link标头(换行符仅出于可读性目的):

Link: <http://api.example.com/foo?page=1&size=10>; rel="first", 
      <http://api.example.com/foo?page=2&size=10>; rel="previous",
      <http://api.example.com/foo?page=4&size=10>; rel="next", 
      <http://api.example.com/foo?page=5&size=10>; rel="last"

检查link relations registered in IANA


为返回记录数,我已经看到一些使用自定义标头的API,例如X-Total-Count,但我不建议这种方法。然后在响应有效负载中发送这些详细信息。