APIs with FastAPI · Chapter 7 of 26

Dependencies

By the end of this chapter you can write a dependency and give it to routes with Depends, read a header in one, stop a request from inside one, chain dependencies and know how often each runs, write a yield dependency with cleanup that always happens, and swap a dependency for another in a test. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Structure and data
  • 4 tasks
  • FastAPI
  • In the all labs plan

The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.

Why you need this

DakiyaGo's API has grown to a dozen routes, and Aman is reading them before the festive rush. The same lines keep turning up. Every list route reads limit and offset and checks them. Every merchant route reads the API key, looks it up, and answers 401 when it is wrong. Imran has found two routes where the copies have drifted: one allows 100 rows a page, the other 50, and one forgot to check the key at all.

Copying the same parameters and checks into every route is how that happens. What you need is a way to write "page this list" or "who is calling" once, and have FastAPI run it before each route that asks for it. That is a dependency, and FastAPI is built around them: the database session in chapter 9, the logged-in user in chapter 13 and the permissions in chapter 14 are all dependencies.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    paging.py: one paging rule for every list

    Sunita's dashboard and the merchants' software both page through long lists. Make an app with two routes, GET /parcels (the parcels in /workspace/data/parcels.json) and GET /pincodes (the pincodes in pincodes.json), that page the same way: query parameters limit (1 to 50, default 10) and offset (0 or more, default 0).

    Each answers an object with exactly four keys: limit and offset as used, total (how many there are in the whole file), and items (the rows after skipping offset, at most limit of them, in the file's order). A limit of 0 or 51, an offset of -1, or a limit that is not a number answers 422.

    Write the paging rule once, as a dependency both routes use: the check looks for one function given to both.

  2. Task 2

    merchant_key.py: who is calling?

    Merchants' software identifies itself with an X-Api-Key header holding the key in /workspace/data/merchants.json. Write a dependency called current_merchant that reads that header and returns the merchant's dictionary from merchants.json, or answers 401 when the header is missing or no merchant has that key.

    Two routes use it: GET /me answers the merchant's id, name and plan (never its api_key), and GET /my/parcels answers an object with merchant_id, count and parcels: every parcel of that merchant from parcels.json, in the file's order.

  3. Task 3

    timing.py: time every request

    Aman wants to know which requests are slow. Write a dependency that yields, given to the whole app so it runs for every route: it notes the time before the yield and, after it, appends an entry with exactly two keys to a list: path (the path that was asked, like /parcels/DKG10007) and ms (how long the request took, in milliseconds, a number).

    Routes: GET /parcels/{awb} answers that parcel from parcels.json, or 404 for an AWB it does not have; GET /slow sleeps 0.2 seconds and answers {"slept": 0.2}; GET /timings answers the list, oldest first. The check asks a parcel, a missing parcel and /slow, then reads /timings: all three must be there, the 404 too. It ignores entries for /timings itself.

  4. Task 4 · interview question

    Interview: test_override.py, a merchant without a key

    Imran wants a test for GET /my/parcels that does not need a real merchant's key in the test file. In test_override.py, write a pytest test called test_sees_only_own_parcels. It imports app and current_merchant from merchant_key.py (task 2), makes current_merchant answer Hawa Mahal Books (the M04 dictionary from merchants.json) through app.dependency_overrides, calls GET /my/parcels with a TestClient and no X-Api-Key header, and asserts the answer is 200 and holds 8 parcels that all belong to M04. Remove the override when the test is done.

    The check runs your test against an app of its own where no key works at all, then against two broken apps (one answers every merchant's parcels, one another merchant's): your test must pass on the first and fail on both broken ones. Run it yourself with pytest test_override.py. The interviewer will ask: what does an override replace, and why is that better than a test key?

What you will learn

  • Depends: a function FastAPI calls for you, with parameters filled from the request.
  • Stopping a request from a dependency, and reading a header.
  • Dependencies of dependencies, and why each runs once per request.
  • yield dependencies: work before the route and cleanup after it.
  • Overriding a dependency in a test.

More in Structure and data

Build "Dependencies" yourself

DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.