In this lab, you'll add server-side pagination to an existing Flask API endpoint. Right now, your API returns all books when a client makes a request to /books. That’s fine with 10 entries, but in production systems, this approach can slow down your app and flood the frontend with too much data.
Your goal is to refactor the endpoint to:
- Accept
?page
and?per_page
query parameters - Return only a subset of records
- Include metadata (like total, page, total_pages) in the response
This mirrors the structure used by APIs across the web from Shopify to Reddit to GitHub.
The starter code includes a Flask app and seed data for books.
To get started:
pipenv install && pipenv shell
cd server
flask db init
flask db migrate -m "initial migration"
flask db upgrade head
python seed.py
python app.py
You can view the API in your browser or using Postman. Test pagination by visiting http://localhost:5555/books?page=1&per_page=5.
Your current /books endpoint returns every book in the database. The frontend team wants this replaced with a paginated response that:
- Uses page and per_page query parameters
- Returns only the requested chunk of data
- Includes metadata like the total number of pages
Backend Requirements:
- Accept
?page=<int>
and?per_page=<int>
viarequest.args
- Use
.paginate()
on your SQLAlchemy query - Return a structured JSON response like:
{
"page": 1,
"per_page": 5,
"total": 30,
"total_pages": 6,
"items": [
{ "id": 1, "title": "Apple Pie" },
// ...
]
}
- page
- per_page
Use the SQLAlchemy .paginate()
method to get the correct books by the query params.
Format response with the proper metadata:
- page
- per_page
- total
- total_pages
- items
Test routes in browser or Postman. Run the test suite with:
pytest
- Commit and push your code:
git add .
git commit -m "final solution"
git push
- If you created a separate feature branch, remember to open a PR on main and merge.
Optional Best Practice documentation steps:
- Add comments to the code to explain purpose and logic, clarifying intent and functionality of your code to other developers.
- Update README text to reflect the functionality of the application following https://makeareadme.com.
- Add screenshot of completed work included in Markdown in README.
- Delete any stale branches on GitHub
- Remove unnecessary/commented out code
- If needed, update git ignore to remove sensitive data
CodeGrade will use the same test suite as the test suite included.
Once all tests are passing, commit and push your work using git
to submit to CodeGrade through Canvas.