其余 API 是否包络



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

我的 API 有一个执行分页的终结点。因此,在响应中,我必须向客户端返回受查询影响的行总数。实际记录的计数。

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

奥赖利 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.

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

谢谢。

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

{
"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"
}
}

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"

检查在 IANA 中注册的链接关系。


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

最新更新