API分页的最佳实践 [英] API pagination best practices

查看:377
本文介绍了API分页的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想吃一些帮助处理一个奇怪的边缘情况与分页API我建设。

I'd love some some help handling a strange edge case with a paginated API I'm building.

像很多的API,这一个大进行分页结果。如果查询/ FOOS,你会得到100个结果(即富#1-100),和/ FOOS?页= 2一个链接,应该返回foo的#101-200。

Like many APIs, this one paginates large results. If you query /foos, you'll get 100 results (i.e. foo #1-100), and a link to /foos?page=2 which should return foo #101-200.

不幸的是,如果富#10从数据中设置的API,消费者使下一个查询之前被删除,/ FOOS?页= 2将由100偏移并返回FOOS#102-201

Unfortunately, if foo #10 is deleted from the data set before the API consumer makes the next query, /foos?page=2 will offset by 100 and return foos #102-201.

这是API消费者谁正试图将所有FOOS一个问题 - 他们将不会收到富#101

This is a problem for API consumers who are trying to pull all foos - they will not receive foo #101.

什么是处理这个问题的最佳做法?我们希望让它轻量级越好(即,避免处理会话,API请求)。从其他API的例子将是极大的AP preciated!

What's the best practice to handle this? We'd like to make it as lightweight as possible (i.e. avoiding handling sessions for API requests). Examples from other APIs would be greatly appreciated!

推荐答案

我不完全确定你的数据是如何处理的,所以这可能会或可能不会工作,但你有没有考虑使用时间戳字段分页?

I'm not completely sure how your data is handled, so this may or may not work, but have you considered paginating with a timestamp field?

当您查询/ FOOS你会得到100个结果。您的API则应该返回是这样的(假设JSON,但如果需要XML相同的原则可以遵循):

When you query /foos you get 100 results. Your API should then return something like this (assuming JSON, but if it needs XML the same principles can be followed):

{
    "data" : [
        {  data item 1 with all relevant fields    },
        {  data item 2   },
        ...
        {  data item 100 }
    ],
    "paging":  {
        "previous":  "http://api.example.com/foo?since=TIMESTAMP1" 
        "next":  "http://api.example.com/foo?since=TIMESTAMP2"
    }

}

刚一说明,只使用一个时间戳依赖于你的结果一个隐含的限价。您可能需要添加一个明确的限制或还使用直到属性。

时间戳可以使用该列表中的最后一个数据项被动态地确定。这似乎或多或少如何Facebook在其图形API (滚动进行分页下到谷底看到分页链接我上面给的格式)。

The timestamp can be dynamically determined using the last data item in the list. This seems to be more or less how Facebook paginates in its Graph API (scroll down to the bottom to see the pagination links in the format I gave above).

一个问题可能是,如果你添加一个数据项,但根据您的描述听起来像他们将被添加到年底(如果没有,让我知道,我会看看我是否能在这个提高)。

One problem may be if you add a data item, but based on your description it sounds like they would be added to the end (if not, let me know and I'll see if I can improve on this).

这篇关于API分页的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆