How to Implement Pagination in Flask API Easily
To implement pagination in a
Flask API, use query parameters like page and per_page to control which data slice to return. Calculate the offset and limit in your database query, then return the paginated results along with metadata like total pages and current page.Syntax
Pagination in Flask API typically uses query parameters to specify the page number and items per page. You extract these parameters from the request, calculate the offset, and limit the query results accordingly.
page: The current page number (usually starts at 1).per_page: Number of items to show per page.offset: Number of items to skip, calculated as(page - 1) * per_page.limit: Number of items to fetch, equal toper_page.
python
from flask import request page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 10)) offset = (page - 1) * per_page # Use offset and per_page in your database query results = Model.query.offset(offset).limit(per_page).all()
Example
This example shows a simple Flask API endpoint that returns paginated user data. It reads page and per_page from the URL query, fetches the correct slice from a mock database, and returns JSON with the data and pagination info.
python
from flask import Flask, request, jsonify app = Flask(__name__) # Mock data: list of user names users = [f"User{i}" for i in range(1, 101)] # 100 users @app.route('/users') def get_users(): page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 10)) total = len(users) start = (page - 1) * per_page end = start + per_page data = users[start:end] return jsonify({ 'page': page, 'per_page': per_page, 'total': total, 'total_pages': (total + per_page - 1) // per_page, 'data': data }) if __name__ == '__main__': app.run(debug=True)
Output
Running the Flask app and visiting /users?page=2&per_page=5 returns JSON with users 6 to 10 and pagination info.
Common Pitfalls
- Not validating
pageandper_pagecan cause errors or unexpected results if users send invalid values. - Forgetting to handle the case when
pageis out of range, which can return empty data without clear info. - Returning all data without pagination can overload the client and server.
- Not including pagination metadata (like total pages) makes it hard for clients to navigate pages.
python
from flask import request, jsonify @app.route('/items') def get_items(): try: page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 10)) if page < 1 or per_page < 1: raise ValueError except ValueError: return jsonify({'error': 'Invalid page or per_page parameter'}), 400 # Assume items is a list of data total = len(items) start = (page - 1) * per_page end = start + per_page if start >= total: return jsonify({'error': 'Page out of range'}), 404 data = items[start:end] return jsonify({ 'page': page, 'per_page': per_page, 'total': total, 'total_pages': (total + per_page - 1) // per_page, 'data': data })
Quick Reference
- Use
pageandper_pagequery parameters to control pagination. - Calculate
offset = (page - 1) * per_pagefor database queries. - Return pagination metadata: current page, per page, total items, total pages.
- Validate input parameters to avoid errors.
- Handle out-of-range pages gracefully.
Key Takeaways
Use query parameters
page and per_page to control pagination in Flask APIs.Calculate offset as
(page - 1) * per_page to fetch the correct data slice.Always validate pagination inputs and handle out-of-range pages to avoid errors.
Return pagination metadata to help clients navigate pages easily.
Avoid sending all data at once to keep API responses efficient and fast.