Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Projects and Practice

Project: Build a Bookstore API with Django REST Framework

Build a complete Django REST Framework bookstore API: models, serializers, viewsets, filtering, search, pagination, staff-only writes, reviews with ratings, query counts and tests.

Time to combine the chapters into one real API. You will build the back end of a small online bookstore in two parts: a catalog that anyone can browse and only staff can change, and reviews that signed-in readers post once per book, with an average rating on every book.

Each part runs in the page. In a real project the code is spread across models.py, serializers.py, views.py, filters.py and urls.py; here it sits in one file so that you can run and change it. Use the same structure in your own project.

The plan

Catalog List, filter, search, sort, paginate
Staff writes Everyone reads, staff edit
Reviews One per user, average rating
Proof Tests and query counts

Requirements first, then code

1 / 2

Requirements

  1. GET /books/ lists books, 4 per page, with the author's name.
  2. Clients can filter by genre and price range, search title and author, and sort by price or year.
  3. Anyone may read; only staff may create, edit or delete books and authors.
  4. Prices must be positive; a year cannot be in the future.
  5. Signed-in users can review a book once (POST /books/{id}/reviews/). Reviews have 1-5 stars.
  6. Each book shows average_rating and review_count without extra queries per book.

Part 1: the catalog

The design choices: a ModelSerializer that writes the author by id but shows the name, a FilterSet for the exact query parameters, SearchFilter and OrderingFilter for free text and sorting, page-number pagination, and one small permission class. See filtering, search and ordering, pagination and permission classes if any part feels unfamiliar.

Python Part 1: the catalog endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
page 1: 6 books, ['Night Trains', 'Salt and Iron', 'The Quiet Harbor', 'Learning Rust Slowly'] | next page: True
fiction under 12: ['The Quiet Harbor']
search 'omar': ['The Quiet Harbor', 'Gardens of Glass']
cheapest first: ['9.99', '12.50', '15.00', '18.25']
anonymous POST -> 403
staff POST -> 201 Ada Lin
invalid POST -> 400 {'price': ['The price must be positive.'], 'year': ['The year cannot be in the future.']}

Read the requirements again and tick them off: pagination, filters, search, ordering, staff-only writes and validation are all covered by about 100 lines. Notice how many decisions were declarations (a list of fields, a class attribute) rather than code. That is DRF's strength.

Part 2: reviews and ratings

Reviews belong to a book and to the logged-in user. The user must never come from the request body, or anyone could post as someone else, so the view sets it. A detail route, @action(detail=True), gives the URL /books/{id}/reviews/ without a second viewset. For the average rating we use annotate(), as in query optimization.

Python Part 2: reviews, ratings and a query budget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
anonymous review -> 403
ann reviews book 1 -> 201
ann again -> {'detail': 'You have already reviewed this book.'}
bob, 4 stars -> 201
bob, 9 stars -> {'stars': ['Ensure this value is less than or equal to 5.']}
Night Trains    rating=4.5 reviews=2
Salt and Iron   rating=3.0 reviews=1
Deep Roots      rating=None reviews=0
queries for the whole list: 1
book 1 reviews: [('bob', 4), ('ann', 5)]

The one-review-per-user rule is enforced twice: the view checks first to give a friendly message, and the database UniqueConstraint protects against two simultaneous requests slipping through. Always back business rules that matter with a database constraint.

Part 3: testing and hardening the project

What would you add before shipping this API?

  • Tests, as in Testing DRF APIs: a matrix of who may do what, a test for each validation error, and assertNumQueries on the list endpoint.
  • Throttling on POST /reviews/ (ScopedRateThrottle, scope reviews) so nobody can flood the book with reviews, see throttling.
  • Authentication: token or JWT login for the front end (token authentication, JWT).
  • Documentation: drf-spectacular and extend_schema for the review action (schema generation).
  • Versioning: put it under /api/v1/ from day one (versioning).
  • Production settings and a health check (deployment).

Extension ideas

  1. Add Order and OrderItem models, and a POST /orders/ endpoint that checks stock inside transaction.atomic() and uses select_for_update() on the books.
  2. Let reviewers edit or delete their own review (an object-level permission, see custom permissions).
  3. Add a GET /books/recommended/ action that returns the five highest-rated books with at least three reviews.
  4. Add cursor pagination to the reviews list and an ordering choice between newest and highest.
  5. Export the catalog as CSV with a custom renderer (renderers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the review view set user=request.user instead of reading it from the body?

    Identity must come from authentication, never from data the client controls.
  2. 2. Why have both a view check and a UniqueConstraint for one review per user?

    Application checks can race; the database constraint is the final guard.
  3. 3. How does the book list show average_rating without a query per book?

    The database computes the aggregates in one grouped query.
  4. 4. Which DRF feature gives the URL /books/{id}/reviews/ without another viewset?

    Extra actions on a ViewSet are routed automatically by the router.

Summary

  • A catalog API is mostly declarations: serializer fields, a FilterSet, search and ordering fields, a pagination class and a small permission class.
  • Staff-only writes use a permission class; validation lives in the serializer.
  • Reviews use a detail @action, set the user on the server, and annotate aggregates instead of counting per row.
  • Back important rules with database constraints, and protect the query budget with tests.
  • Next steps: tests, throttles, authentication, documentation, versioning and production settings.

Next: Project: A Task Tracker with Token Authentication