Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Task Tracker API with Token Authentication

Build a multi-user task tracker with Django REST Framework: sign-up and token login, per-user tasks, object permissions, custom actions for completing and summarizing, filters and tests.

The bookstore project had a public catalog. Now you will build the opposite: an API where everything belongs to a user. A task tracker is a classic exercise because it contains the problems of every real multi-user API: sign-up, login, "only my data", status changes, summaries, and abuse protection.

The finished API:

Method and URL What it does Who
POST /signup/ create an account, return a token anyone (throttled)
POST /login/ exchange username and password for a token anyone
POST /logout/ delete the caller's token signed in
GET /tasks/?status=open&search=... my tasks, filtered signed in
POST /tasks/ create a task signed in
PATCH /tasks/{id}/ edit my task owner
POST /tasks/{id}/complete/ mark done owner
GET /tasks/summary/ counts per status, overdue count signed in

How a request flows

Token Authorization: Token abc...
Who are you? TokenAuthentication sets request.user
Scoped queryset Only your rows exist for you
Serializer Validates and saves with owner set

Scoping the queryset is the strongest ownership check

1 / 2

Part 1: accounts, tokens and per-user tasks

Design decisions, each one a lesson from earlier chapters:

  • Tokens. Simple, revocable, perfect for a mobile app or script (token authentication). Login and sign-up return the token; logout deletes it.
  • Scoped queryset. get_queryset() returns only the caller's tasks. A task belonging to someone else is simply a 404, so IDs of other people's data are never confirmed to exist.
  • Owner from the server. perform_create sets owner=request.user. The serializer does not expose owner.
  • Passwords are handled by create_user() and Django's validators, never stored in plain text and never returned.
Python Part 1: sign-up, login, logout and private tasks

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
tasks without a token -> 401
weak password -> {'password': ['Ensure this field has at least 8 characters.']}
signup -> ann token length 40
duplicate name -> {'username': ['That username is taken.']}
created (status field ignored on input): {'id': 1, 'title': 'Plan the week', 'status': 'open'}
bob lists: []
bob opens ann's task -> 404
login -> ['token']
logout -> 204
ann's old token afterwards -> 401

Study the three "ownership" results: the anonymous caller gets 401, Bob gets an empty list, and Bob opening Ann's task gets 404. Nothing in the view says "check that the owner matches"; the queryset itself is the check, so you cannot forget it on one endpoint.

Part 2: custom actions, summaries and filters

A REST resource sometimes needs verbs that are not plain CRUD. "Complete this task" is an action on one task; "summary" is an action on the whole collection. In a ViewSet both are @action methods; the router adds their URLs. Prefer small action endpoints to a free-form PATCH {"status": "done"}, because you can enforce rules (a done task cannot be completed twice) in one place.

Python Part 2: complete, summary, overdue filter

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
past due date -> {'due': ['The due date cannot be in the past.']}
summary: {'open': 4, 'done': 0, 'overdue': 2}
complete #1 -> done
complete #1 again -> 409
summary: {'open': 3, 'done': 1, 'overdue': 1}
overdue list: [('Renew passport', True)]
open list: ['Renew passport', 'Book flights', 'Call dentist']

Notes on the design:

  • Count(..., filter=Q(...)) computes several statistics in one query, instead of three .count() calls.
  • The action reuses get_object(), so it automatically applies the queryset scope, permissions and 404 handling.
  • 409 Conflict is a good answer for "this state change is not possible now". Pick a status code on purpose; clients rely on it.
  • Hand-written get_queryset() filtering is fine for two parameters. As filters grow, move to django-filter.

Part 3: harden it

  1. Throttle the public endpoints. Sign-up and login accept anonymous traffic, so give them a scoped throttle such as 5/min (throttling). Without it, someone can guess passwords all day.
  2. Expire tokens or switch to JWT with short access tokens and a refresh token (JWT).
  3. Test the ownership rule. Two users, one task, and a test that the stranger gets 404 for GET, PATCH, DELETE and POST .../complete/ (testing security).
  4. Add pagination before the list grows (pagination).
  5. Make it HTTPS-only in production, or tokens can be read on the network (deployment).

Extension ideas

  • Tags (many-to-many) with a ?tag= filter and prefetch_related.
  • Shared tasks: a TaskShare model and an object permission that lets collaborators read or edit (custom permissions).
  • A PATCH /tasks/reorder/ action that accepts a list of IDs and saves positions in one transaction.
  • Webhook or email notification when a task becomes overdue (a management command run by cron).
  • A change history table recording who changed what.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Bob requests Ann's task id. What does the scoped get_queryset() return, and why is it good?

    The object is simply not in Bob's queryset, so the generic view answers 404.
  2. 2. Why is the status field read-only on the task serializer?

    Putting a state change into an action lets you apply business rules in one place.
  3. 3. What does Count('id', filter=Q(status='open')) allow?

    Conditional aggregation computes open, done and overdue totals in a single grouped query.
  4. 4. Which status code suits 'complete' on a task that is already done?

    409 says the request conflicts with the current state of the resource.

Summary

  • Multi-user APIs revolve around ownership: scope the queryset, set the owner on the server, never expose it as input.
  • Token auth gives sign-up, login and logout with a few small views.
  • @action adds domain verbs (complete, summary); aggregates with conditional Count keep summaries to one query.
  • Use precise status codes, throttle public endpoints, test the stranger case, and serve over HTTPS.

Next: Project: A Blog API with JWT, Comments and Moderation