Skip to the page

FastAPI · mid

Dependencies, database sessions, JWT login and lifespan

Depends() builds a tree of callables per request, such as a database session and the current user. Code after yield may run after the response is sent, so commit inside the request. Shared objects live in lifespan.

The notes

What you must know

  • A dependency is any callable passed to Depends(), often Annotated[Session, Depends(get_db)]. FastAPI resolves the tree per request. Within one request each dependency runs once and is reused (use_cache=True).
  • get_db with yield opens a session, yields it and closes it in finally. get_current_user depends on the token (OAuth2PasswordBearer) and get_db, and raises 401 when the token is bad.
  • By default, code after yield runs after the response is sent. If a commit there fails, the client already got 200. Commit inside the request (a with db.begin() block in the endpoint or service) so a failure becomes an error. If you catch an exception after yield, raise it again.
  • Router-level dependencies: APIRouter(dependencies=[Depends(...)]). In tests: app.dependency_overrides[get_current_user] = lambda: user, cleared afterwards. There is no container and no singleton by default.
  • Lifespan: an async context manager passed as FastAPI(lifespan=...). Code before yield runs at startup, after yield at shutdown. Keep objects on app.state. @app.on_event is removed in Starlette 1.0.
  • Lifespan runs once per worker process: 4 workers means 4 engines, pools and model copies. A shared httpx.AsyncClient reuses connections; close it at shutdown. TestClient used as a context manager runs lifespan.
  • JWT: jwt.decode(token, SECRET, algorithms=["HS256"], options={"require": ["exp", "sub"]}), catch InvalidTokenError and raise HTTPException(401, headers={"WWW-Authenticate": "Bearer"}). A fixed algorithm list blocks the none and algorithm-confusion tricks.
  • A JWT payload is only base64, not encrypted. Use short access tokens with rotating refresh tokens. Hash passwords with Argon2 and give the same error and similar timing for no user and wrong password. A cookie token needs CSRF protection; a token in JavaScript memory is open to XSS.

The red pen

Common traps: mistake → fix

  • Mistake: The code after yield runs before the response

    Fix: by default it runs after the response is sent.

  • Mistake: Swallow the exception in a yield dependency and the client will see it

    Fix: it is lost; re-raise.

  • Mistake: A JWT is encrypted

    Fix: it is signed, and anyone can read the payload.

  • Mistake: Dependencies are singletons like Spring beans

    Fix: they are functions run per request.

Easy to hard

Questions interviewers ask, easy to hard

  1. How does dependency injection work in FastAPI?
  2. How does each request get a database session and the current user?
  3. Why did the app show Transfer done but the money never moved?
  4. What replaced @app.on_event("startup")?
  5. Write get_current_user with a Bearer JWT.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview