Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Practice: DRF Exercises, Pitfalls and Interview Questions

Practice Django REST Framework with hands-on exercises that check themselves, a list of the most common mistakes, capstone ideas and interview questions with short, accurate answers.

Reading about an API framework teaches you the vocabulary. Building and breaking things teaches you the framework. This last lesson gives you work to do: two exercises that check themselves in the editor, ten more exercises to do in your own project, the mistakes that trip people up most often, and the questions that come up in DRF interviews.

How to practice

Try first Do not peek at the answer
Test it Write the test before the fix
Break it Send bad input and wrong users
Count queries Make slow endpoints fast

An exercise you cannot fail teaches little

1 / 2

Exercise 1: a serializer with rules

A shop wants a promo code API. A code needs: an upper-case code of 4-12 letters or digits, a percent from 1 to 90, and starts_on / ends_on dates where the end is after the start. The editor below contains a serializer that checks none of that, and a checker that tests the rules. Read the output, then fix the serializer until every line says PASS.

Hints: use validate_code() for one field and validate() for rules that compare fields; use serializers.IntegerField(min_value=..., max_value=...) for ranges. A field-level validator should return the (possibly changed) value or raise ValidationError.

Python Exercise 1: make the checks pass

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
PASS a valid promo is accepted
FAIL the code is stored in upper case
FAIL a short code is rejected
FAIL a code with spaces is rejected
FAIL percent 0 is rejected
FAIL percent 95 is rejected
FAIL an end before the start is rejected
FAIL an end equal to the start is rejected

Here is one solution. Compare it with yours only after you tried.

Python
class PromoSerializer(serializers.Serializer):
    code = serializers.CharField()
    percent = serializers.IntegerField(min_value=1, max_value=90)
    starts_on = serializers.DateField()
    ends_on = serializers.DateField()

    def validate_code(self, value):
        value = value.strip().upper()
        if not (4 <= len(value) <= 12 and value.isalnum()):
            raise serializers.ValidationError("Use 4-12 letters or digits.")
        return value

    def validate(self, attrs):
        if attrs["ends_on"] <= attrs["starts_on"]:
            raise serializers.ValidationError("The end date must be after the start date.")
        return attrs

If you need a refresher, see the serializer lessons and validation.

Exercise 2: private notes

Build a notes API where users see only their own notes. A stranger must get 404, not 403; creating a note must set the owner automatically; and the owner must not be writable. The editor again holds a flawed version: it lists every note to everyone and trusts the body. Fix get_queryset(), perform_create() and the serializer.

Python Exercise 2: private notes

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
PASS creating returns 201
FAIL the owner is the caller, not the value sent in the body
FAIL bob's list does not contain ann's note
FAIL bob gets 404 for ann's note
FAIL bob cannot delete ann's note
FAIL ann still sees her note

Reference solution: read_only_fields = ["owner"] on the serializer, get_queryset() returning Note.objects.filter(owner=self.request.user) (and basename="note" in the router, because the queryset attribute is gone), and serializer.save(owner=self.request.user) in perform_create(). The same ideas appear in the task tracker project.

Ten more exercises for your own project

  1. Pagination swap. Take a list endpoint and compare PageNumberPagination with CursorPagination. Insert a row between two page requests and see which style duplicates or skips rows (pagination).
  2. Filter set. Add min_price, max_price, and a q search filter with django-filter; return 400 for a bad number (filtering).
  3. N+1 hunt. Add assertNumQueries to an endpoint that serializes a related object; make it fail, then fix it (query optimization).
  4. Object permission. Allow only the author or a moderator to delete; test the stranger (custom permissions).
  5. Throttle. Rate-limit the login endpoint to 5 a minute per IP and test it with a fake clock (throttling).
  6. Versioning. Introduce /v2/ with a changed field shape while /v1/ stays the same (versioning).
  7. OpenAPI. Generate the schema, fix every spectacular warning, and add examples to one endpoint (schema generation).
  8. Custom action. Add POST /orders/{id}/cancel/ that is allowed only while the order is pending; return 409 otherwise.
  9. Uniform errors. Write a custom exception handler that returns {"error": {"code": ..., "message": ..., "fields": ...}} for every failure.
  10. Deploy. Run check --deploy, set up gunicorn locally, put nginx in front and confirm HTTPS-only headers (deployment).

Capstone ideas

Choose one and build it with tests, docs and a deployment: a library lending system (books, copies, loans, due dates, fines), a ticket booking API (events, seats, holds that expire, double-booking prevention with select_for_update), a habit tracker (streak calculations and weekly summaries), or a marketplace (listings, offers, messaging, moderation).

The most common DRF mistakes

Mistake What happens Fix
Forgetting read_only_fields for owner, status, timestamps Clients can set them Mark them read-only; set them in perform_create()
fields = "__all__" on models with sensitive columns Leaks internals, later migrations change the API List the fields explicitly
No queryset scoping, only has_permission Any user can open any ID (IDOR) Filter in get_queryset() or add an object permission
Relying on has_object_permission in a list view It never runs for lists Filter the queryset
N+1 queries from nested serializers Slow endpoints select_related, prefetch_related, annotate
Unpaginated list Huge responses, timeouts Set a default pagination class
SerializerMethodField doing a query per row Hidden N+1 Annotate or prefetch
Posting nested data without format="json" in tests Confusing 400 errors Always pass format="json"
Catching Exception and returning 200 with an error text Clients cannot detect failure Raise DRF exceptions, return the right status
DEBUG=True and browsable API in production Information leaks, slow forms JSON renderer only; DEBUG=False
Same SECRET_KEY used as token signing key everywhere One leak breaks all Separate secrets per environment
Business rule only in the view The admin or a script bypasses it Put rules in models/services; back them with constraints

Interview questions and short answers

What is the difference between APIView, generic views and ViewSet? APIView gives you the request/response handling and you write each method. Generic views add queryset/serializer handling and mixins for standard CRUD. ViewSets group the related actions in one class and let a router build the URLs.

What does a serializer do? It converts model instances and other data to Python primitives for rendering (to_representation), and validates incoming data and turns it into validated Python values (to_internal_value, is_valid, save).

Serializer vs ModelSerializer? ModelSerializer generates fields, validators and the create/update methods from a model; Serializer is fully manual and fits data that is not a model.

validate_<field> versus validate? The first validates one field, the second validates the whole data and can compare fields. Errors from validate() appear under non_field_errors.

Authentication vs permission vs throttling? Authentication decides who the caller is, permissions decide whether that caller may do this, throttling decides whether they may do it again right now. They run in that order.

401 or 403? 401 means "not authenticated" and is sent only when the first authentication class provides a WWW-Authenticate header; 403 means authenticated (or no challenge possible) but not allowed.

How do you stop one user from reading another user's data? Scope the queryset to the user, and/or use object-level permissions. Test with a second user.

has_permission vs has_object_permission? The first runs for every request on the view; the second runs only when get_object() is called (and check_object_permissions is invoked), so it never protects list endpoints.

How do you avoid N+1 queries? select_related for foreign keys, prefetch_related for many-valued relations, annotate for aggregates, and assertNumQueries to keep it fixed.

Token vs JWT vs session authentication? Sessions suit browsers on your own domain and need CSRF protection. DRF tokens are random database-backed keys, easy to revoke. JWTs are signed, self-contained tokens that avoid a database lookup, but need short lifetimes and a refresh and revocation strategy.

How do you version an API? URL path, header, query or host name versioning classes set request.version; choose serializers or behaviour from it, and deprecate old versions with notice.

How do you paginate large tables? Cursor pagination for large, changing tables; page number or limit/offset for small ones. Always set a maximum page size.

How do you test an API? APITestCase and APIClient with force_authenticate; test success, refusals, bad input and query counts.

How do you document an API? Generate an OpenAPI schema with drf-spectacular, annotate with extend_schema, and publish Swagger UI or Redoc.

What would you check before deploying? DEBUG off, secrets from the environment, check --deploy, HTTPS, CORS origins, JSON-only renderers, shared cache for throttles, migrations plan, logging and monitoring.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A list endpoint returns every user's notes although the view has an IsOwner object permission. Why?

    has_object_permission runs only from get_object(). Lists need a filtered queryset.
  2. 2. In which order do the three access-control steps run for each request?

    DRF authenticates first, then checks permissions, then throttles; only after that does your view method run.
  3. 3. Which is the best fix when a client can post an owner id in the request body?

    Server-controlled values must be read-only for clients and set by trusted code.
  4. 4. What is the quickest way to prove an endpoint no longer has an N+1 problem?

    A query-count test is exact and repeatable.
  5. 5. Which settings change does the most to protect a public DRF API from floods?

    Throttling with a shared cache limits request rates per client across all worker processes.

Summary

  • Practice by fixing broken code: validation rules in serializers, ownership in querysets, server-controlled fields.
  • The common mistakes are mostly about trusting client input, forgetting list-level scoping, and hidden N+1 queries.
  • Know the basic distinctions: view types, serializer types, authentication versus permissions versus throttling, 401 versus 403.
  • Pick a capstone, add tests, documentation and a production setup, and you have a portfolio-ready API.

You have reached the end of this tutorial. Go back to the track page to review any chapter, or start a new project.

Next: Back to the Django REST Framework course