Cursor-based pagination helps you get data in small parts without missing or repeating items. It uses a marker (cursor) to remember where you left off.
Cursor-based pagination in Rest API
Start learning this pattern below
Jump into concepts and practice - no test required
GET /items?limit=10&cursor=abc123limit sets how many items to get per page.
cursor is a token that points to where to start the next page.
GET /products?limit=5GET /products?limit=5&cursor=eyJpZCI6MTAwfQ==This is a simple web server using Flask. It returns items in pages. You ask for a page with a limit and an optional cursor. The server finds where to start, sends that many items, and gives a cursor for the next page.
from flask import Flask, request, jsonify app = Flask(__name__) # Sample data: list of items with IDs 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)) cursor = request.args.get('cursor') # Find start index based on cursor start_index = 0 if cursor: try: start_id = int(cursor) # Find the index of the item with id == start_id for idx, item in enumerate(items): if item['id'] == start_id: start_index = idx + 1 break except ValueError: pass # Get the slice of items page_items = items[start_index:start_index + limit] # Prepare next cursor if len(page_items) == limit and (start_index + limit) < len(items): next_cursor = str(page_items[-1]['id']) else: next_cursor = None return jsonify({ 'items': page_items, 'next_cursor': next_cursor }) if __name__ == '__main__': app.run(debug=True)
Cursor-based pagination is more reliable than page-number pagination when data changes often.
The cursor is usually an encoded value like an ID or timestamp.
Always return the next cursor in the response so the client can request the next page.
Cursor-based pagination uses a marker to get the next set of data.
It helps avoid missing or repeating items when data changes.
Clients send the cursor to get the next page, and servers return a new cursor if more data exists.
Practice
What is the main purpose of cursor-based pagination in REST APIs?
Solution
Step 1: Understand cursor-based pagination concept
Cursor-based pagination uses a marker (cursor) to fetch the next set of data instead of page numbers.Step 2: Identify the main purpose
This method helps efficiently retrieve data in chunks and avoid missing or repeating items when data changes.Final Answer:
To efficiently fetch the next set of data using a marker -> Option BQuick Check:
Cursor-based pagination = fetch next data with marker [OK]
- Confusing cursor with page number
- Thinking it sends all data at once
- Assuming it sorts data alphabetically
Which of the following is the correct way to include a cursor in a REST API request URL?
GET /items?____=abc123Solution
Step 1: Identify the query parameter for cursor
Cursor-based pagination uses a parameter namedcursorto mark the position for the next data fetch.Step 2: Match the parameter in the URL
The URL should include?cursor=abc123to pass the cursor value.Final Answer:
cursor -> Option AQuick Check:
Cursor parameter in URL = cursor [OK]
- Using 'page' or 'offset' which are for offset pagination
- Confusing 'limit' with cursor
- Leaving out the cursor parameter
Given this API response for cursor-based pagination:
{
"data": ["item4", "item5"],
"next_cursor": "xyz789"
}What should the client do to get the next page of data?
Solution
Step 1: Read the response for next cursor
The response includes anext_cursorvalue "xyz789" which marks the next data position.Step 2: Use the cursor in the next request
The client should send a request with?cursor=xyz789to get the next page.Final Answer:
Send a request with ?cursor=xyz789 -> Option AQuick Check:
Use next_cursor value as cursor parameter [OK]
- Using page or offset parameters instead of cursor
- Ignoring next_cursor and repeating last request
- Sending limit without cursor
Consider this code snippet for fetching paginated data using cursor-based pagination:
cursor = None
while True:
response = api.get_items(cursor=cursor)
process(response.data)
cursor = response.next_cursor
if not cursor:
breakWhat is the likely bug in this code?
Solution
Step 1: Analyze the code structure
The code fetches data, processes it, then assignscursor = response.next_cursorwithout checking ifnext_cursoris empty string.Step 2: Potential infinite loop
Ifnext_cursoris an empty string, the conditionif not cursorwill be true and break the loop, so no infinite loop occurs. But if the check is incorrect or cursor is None, it breaks. However, the main issue is ifnext_cursoris missing, it raises an error.Step 3: Proper handling
Should check ifnext_cursorexists and is truthy before assigning and breaking.Final Answer:
It may cause an infinite loop ifnext_cursoris empty string -> Option DQuick Check:
Check for empty or missing cursor carefully [OK]
- Assuming next_cursor always exists
- Not breaking loop on missing cursor
- Updating cursor after break
You have an API that returns data with cursor-based pagination. The API returns the following responses in sequence:
1. {"data": ["a", "b"], "next_cursor": "c1"}
2. {"data": ["c", "d"], "next_cursor": "c2"}
3. {"data": ["e"], "next_cursor": null}You want to collect all items without duplicates even if the API sometimes returns overlapping data due to data changes. Which approach is best?
Solution
Step 1: Understand overlapping data issue
Cursor-based pagination can return overlapping items if data changes during pagination, causing duplicates.Step 2: Choose a method to avoid duplicates
Using a set to store items as they are fetched avoids duplicates immediately and efficiently.Step 3: Evaluate other options
Removing duplicates after fetching all pages (list) is less efficient. Ignoring duplicates or fetching only first page is incorrect.Final Answer:
Use a set to store items as you fetch each page to avoid duplicates immediately -> Option CQuick Check:
Use set to avoid duplicates during fetch [OK]
- Assuming API never returns duplicates
- Removing duplicates only after all data fetched
- Fetching only first page to avoid duplicates
