Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 50 ยท Practice, interviews and cheat sheet

Exercises with solutions

Practice FastAPI with 12 graded exercises on parameters, models, dependencies, authentication and databases. Every solution runs live and checks itself.

You learn FastAPI by writing endpoints, not by reading about them. This page gives you 12 exercises, ordered from easy to demanding, covering request parameters, Pydantic models, dependencies, authentication and databases. Each group has a runnable solution that checks itself with assertions, so you can compare your own attempt against something that is known to work.

The best way to use the page: read an exercise, close the page, write your own version in a TryIt editor from an earlier lesson (or on your machine), and only then open the solution. If your version behaves the same way, you are done, even if the code looks different.

How to practice

Read the task Note the exact URLs and codes.
Write it yourself No peeking at the solution.
Test it Call it with the client.
Compare Same behavior is a pass.
1 / 2

Every solution below uses the same small helper: call() sends a request to the app in-process (see Your first endpoint and the test client), and check() prints ok or FAILED for each expectation.

Level 1: Parameters (exercises 1-4)

Exercise 1: path parameter. GET /square/{n} takes an integer and returns {"n": 4, "square": 16}. A non-integer such as /square/four must produce 422.

Exercise 2: query parameters. GET /search takes a required q (at least 2 characters) and an optional limit (default 3, between 1 and 10). It returns the words from a fixed list that contain q, case-insensitively, cut to limit.

Exercise 3: path with slashes. GET /files/{path} must accept values such as docs/guide/intro.md in one parameter and return {"folder": "docs/guide", "name": "intro.md"}. (Hint: a path converter, see Path parameters.)

Exercise 4: header. GET /secret requires a header X-Token: letmein. Without it the answer is 401 with {"detail": "Missing or wrong token"}.

Python Solutions 1-4

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 details worth noticing: {path:path} lets one parameter contain slashes, Query(min_length=2) and Query(ge=1, le=10) turn rules into automatic 422 responses, and a header parameter named x_token is matched to X-Token because FastAPI converts underscores to hyphens.

Level 2: Models (exercises 5-7)

Exercise 5: request validation. POST /products accepts name (2 to 30 characters), price (greater than 0) and optional tags (a list of strings, empty by default). It answers 201 with the stored product including an id.

Exercise 6: hide a field. Products also have an internal cost. The create body accepts it, but no response may ever show it. Use separate input and output models, or response_model, see Response models and nested data.

Exercise 7: partial update. PATCH /products/{id} changes only the fields that were sent. Sending {"price": 12} must keep the name and tags. Unknown id gives 404. (Hint: model_dump(exclude_unset=True), see PUT, PATCH and partial updates.)

Python Solutions 5-7

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 patch model makes every field optional with a None default, and exclude_unset=True is what separates "not sent" from "sent as None". Without it, a missing field would overwrite the stored value.

Level 3: Dependencies and auth (exercises 8-10)

Exercise 8: shared parameters. Write a dependency pagination that reads skip (default 0, at least 0) and limit (default 5, 1 to 20) and returns a small object. Use it in GET /numbers, which returns slices of the numbers 1 to 30.

Exercise 9: API key. GET /reports needs a header X-API-Key. Missing key: 401. A key that exists but belongs to a disabled client: 403. A valid key: 200 with the client name. Keep the check in one dependency.

Exercise 10: roles. Tokens map to users with a role. GET /admin/stats is for role admin only. Build it as a dependency factory, require_role("admin"), that returns a dependency. No token: 401, wrong role: 403.

Python Solutions 8-10

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.

Exercise 10 shows the pattern behind most real permission systems: a function that returns a dependency. The endpoint's signature states its requirement (require_role("admin")), so a reader sees the rule without opening the function body. Roles, scopes and permissions builds on it.

Level 4: Database (exercises 11-12)

Exercise 11: database dependency and conflicts. Create a table users (id, email UNIQUE). POST /users inserts an email and answers 201. A second insert of the same email must answer 409, not 500. The connection comes from a dependency that uses yield.

Exercise 12: filtering and pagination. GET /users accepts an optional domain filter (for example example.com), plus offset and limit, and returns {"total": N, "items": [...]}, where total counts all matches, not only the returned page. Always sort by id. Use parameters in the SQL, never string formatting.

Python Solutions 11-12

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.

In exercise 11 the database itself enforces uniqueness. Checking "does this email exist?" first and then inserting has a race window: two requests can both pass the check. Catching the integrity error is the only reliable approach. CRUD, filtering and pagination goes further with keyset pagination and with the same pattern in SQLAlchemy.

Extra challenges

When all twelve pass, try these without a solution:

  • Add GET /products/{id} with a 404 error body of your own design and use it from exercise 7.
  • Return a Link or X-Total-Count header for exercise 12 instead of the total field.
  • Write the exercise 10 checks as a test function list, with a fresh app for each (see Testing FastAPI apps).
  • Replace the token dictionary in exercise 10 with signed tokens from OAuth2 password flow and JWT.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 7, why is model_dump(exclude_unset=True) used?

    exclude_unset drops fields that were not part of the request, so missing fields do not overwrite stored values with defaults.
  2. 2. Which status code does exercise 9 return for a valid API key that belongs to a disabled client?

    The caller is identified, but not allowed: that is 403. 401 is for missing or unknown credentials.
  3. 3. Why is catching sqlite3.IntegrityError better than checking for the email before inserting?

    A check-then-insert sequence has a race window. The UNIQUE constraint closes it, and you translate the error into a 409.
  4. 4. What does require_role("admin") return in exercise 10?

    It is a factory: calling it builds a dependency (the inner checker) configured for that role, which Depends then calls per request.

Summary

  • Practice by writing the endpoint first and comparing the behavior with the solution afterward.
  • Parameters: path converters, Query() constraints and header parameters turn rules into 422/401 answers.
  • Models: separate input, output and patch models; response_model hides internal fields; exclude_unset enables partial updates.
  • Dependencies: shared parameter objects, API-key checks and dependency factories keep endpoints short.
  • Databases: use a yield dependency, parameterized SQL, and turn integrity errors into 409.

Next, learn which mistakes catch almost everyone in Common FastAPI pitfalls.