Keyset pagination helps load data faster by using a fixed point to continue fetching results instead of counting all items each time.
Keyset pagination for performance in Rest API
GET /items?limit=10&after_id=123
limit sets how many items to fetch per page.
after_id tells the server to return items with IDs greater than this value.
GET /products?limit=20&after_id=50
GET /messages?limit=15&after_id=200
GET /posts?limit=10This simple REST API returns items in pages using keyset pagination. It uses the 'after_id' query to fetch items with IDs greater than the given value. If no 'after_id' is given, it returns the first page.
from flask import Flask, request, jsonify app = Flask(__name__) # Sample data: list of items with id and name items = [{'id': i, 'name': f'Item {i}'} for i in range(1, 101)] @app.route('/items') def get_items(): limit = int(request.args.get('limit', 10)) after_id = request.args.get('after_id') if after_id is not None: after_id = int(after_id) filtered = [item for item in items if item['id'] > after_id] else: filtered = items result = filtered[:limit] return jsonify(result) if __name__ == '__main__': app.run(debug=True)
Keyset pagination is faster than offset pagination because it avoids counting or skipping rows.
Use a unique and indexed column (like an ID) for the cursor to keep results consistent.
Remember to handle the case when there are no more items to fetch.
Keyset pagination uses a fixed point (cursor) to fetch the next page of results efficiently.
It is great for large datasets and real-time feeds where counting all items is slow.
Use query parameters like limit and after_id to control pagination.