Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 50 ยท Projects

Project: Blog API with auth

Build a blog API with FastAPI: register and log in, signed tokens, posts and comments, ownership permissions (401 vs 403), and paginated public lists.

This project combines almost everything in the course into one service: accounts with hashed passwords, login that returns a signed token, a public blog that anyone can read, and write operations that only signed-in users may perform, with rules about whose posts and comments they may change. It is the shape of most real APIs: public reads, authenticated writes, and ownership checks.

The service keeps its data in dictionaries so that the security logic stays in the foreground. Swapping them for SQLAlchemy tables is a mechanical change (see SQLAlchemy with FastAPI). Password hashing and tokens come from Password hashing and user accounts and OAuth2 password flow and JWT.

The design

Write down who may do what before you write a line of code. Public means no token needed.

Endpoint Who may call it Rule
POST /register Anyone Unique username, password at least 8 characters
POST /login Anyone Returns a token; same error for wrong user or password
GET /me Signed in Returns your profile
GET /posts, GET /posts/{id} Anyone Paginated, newest first
POST /posts Signed in You become the author
PATCH /posts/{id}, DELETE /posts/{id} The post's author Others get 403
GET /posts/{id}/comments Anyone Paginated
POST /posts/{id}/comments Signed in You become the comment's author
DELETE /comments/{id} Comment author or post author Others get 403

401 or 403?

401 We do not know who you are.
403 We know you, but you may not.
404 That post does not exist.

Check existence first, then permission.

1 / 2

Step 1: passwords and signed tokens

The first example builds the two security helpers in isolation. Passwords are stored as salted PBKDF2 hashes, never as text. A token is payload.signature: the payload says who the user is and when the token expires, and the signature is an HMAC over the payload using a secret only the server knows. Anyone can read the payload, but nobody can change it without breaking the signature.

Both functions take the current time as a parameter. That small design choice makes expiry testable: you can "wait" an hour by passing a bigger number. The real browser Python build lacks hashlib.pbkdf2_hmac, so a short stand-in built on hmac is used, as in the earlier lessons. It uses very few rounds to stay fast here; in production use a library such as pwdlib with Argon2, or at least hundreds of thousands of PBKDF2 rounds. The token code is a teaching stand-in for PyJWT.

Python Password hashes and signed, expiring tokens

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.

The tampered token keeps Ada's signature but swaps in a payload that claims to be admin. The signature no longer matches, so it is rejected. That is the whole security idea of a signed token.

Step 2: the current user dependency

Every protected endpoint needs "the signed-in user". Write it once as a dependency (Dependencies) that reads the Authorization: Bearer <token> header, validates the token, loads the user and raises 401 otherwise. Endpoints then just declare user: CurrentUser.

Ownership checks are the second layer and live inside the endpoint, because only the endpoint knows which post is involved. The order is important: first look the object up (404 if missing), then compare owners (403 if different). A tiny helper keeps that rule in one place.

Lists are paginated with limit (at most 50) and offset, newest first, and the total goes into an X-Total-Count header as in the to-do project. Users are never returned directly: the UserRead schema has no password hash (Response models and nested data).

Step 3: the complete service

The whole service follows. create_app() gives each call its own empty data and its own clock, and the script after it plays a short story with two users, Ada and Bob. Read the printed lines in order and compare each with the table in the design section.

Python The blog API: register, login, posts, comments, permissions

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.

Check the story against the design table. Registration conflicts are 409, a short password is a 422, and a wrong password gives the same 401 message you would get for an unknown user, so attackers cannot learn which usernames exist. Bob editing Ada's post gets 403 (he is signed in, but not the owner) while a post that does not exist gets 404, and the same post deleted by its author disappears. Bob may not delete Ada's comment, but Ada, as the post's author, may delete Bob's. Finally the token stops working after the clock moves one hour, and a token with an altered signature is refused.

What to harden before production

This service teaches the structure, but a real deployment needs more:

  1. Real hashing and JWT libraries. Replace the stand-ins with pwdlib (Argon2) and PyJWT, and load the secret from the environment (Settings and configuration).
  2. Rate limiting on /login and /register, to slow down password guessing (API keys and security practices).
  3. Refresh tokens so access tokens can stay short-lived.
  4. A database with a unique index on username, so two simultaneous registrations cannot both succeed (the dictionary check is only safe because this app is single-process).
  5. Roles, for example an admin who may delete any post (Roles, scopes and permissions).
  6. Tests like the ones in Testing FastAPI apps: one for each row of the permission table, and one for each error code.
  7. HTTPS only, because a bearer token sent over plain HTTP can be stolen (Deployment).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A signed-in user tries to edit another user's post. Which response is correct?

    The user is authenticated, so it is not a 401. They are known but not allowed, which is 403.
  2. 2. Why does /login return the same message for an unknown username and for a wrong password?

    Different messages would let anyone test whether an account exists. A single message reveals nothing.
  3. 3. What stops someone from editing a token's payload to claim they are another user?

    The payload is only encoded, not secret. Integrity comes from the signature, which only the holder of the secret can produce.
  4. 4. In the endpoint code, why is the post looked up before the ownership check?

    Ownership can only be compared once the object is found. A missing object is a 404.

Summary

  • Decide a permission table first: who may call each endpoint, and which status each failure returns.
  • Store only salted password hashes; make login errors identical for unknown users and wrong passwords.
  • A signed token carries the user and an expiry; pass the clock in so expiry is testable.
  • One current_user dependency produces 401; ownership checks inside endpoints produce 403, after the 404 check.
  • Paginate public lists with a bounded limit and report the total in a header.
  • Never return password hashes: use a response schema without them.

You now have the full toolkit: parameters, models, dependencies, security, databases, tests and deployment. The next step is a more demanding one: the Production-ready service project.