new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Tutorial · all subjects

dependencies

45 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Reuse existing dependencies in decorator

You can reuse a normal dependency that returns a value in the path operation decorator even though the returned value won't be used. The dependency will still be executed.

Add dependencies to path operation decorator

The path operation decorator accepts an optional argument `dependencies` which should be a list of Depends() objects. These dependencies will be executed and solved the same way as normal dependencies, but their return values (if any) will not be passed to the path operation function.

When to use dependencies in decorator

Use dependencies in the path operation decorator instead of declaring them as function parameters when you don't need the return value of a dependency inside your path operation function, or when the dependency doesn't return a value but still needs to be executed. This avoids unused parameter warnings from editors and prevents confusion for new developers.

Dependencies in decorator can declare request requirements

Dependencies added to the path operation decorator can declare request requirements like headers and other sub-dependencies, the same way as normal dependencies.

Dependencies in decorator can raise exceptions

Dependencies added to the path operation decorator can raise exceptions just like normal dependencies.

Class dependency example with shortcut syntax

Example of using the Depends() shortcut for class dependencies: from typing import Annotated from fastapi import FastAPI, Depends class CommonQueryParams: def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100): self.q = q self.skip = skip self.limit = limit app = FastAPI() @app.get("/items/") async def read_items(commons: Annotated[CommonQueryParams, Depends()]): return commons With the shortcut, Depends() has no parameters and FastAPI infers the class to instantiate from the type annotation.

What makes a dependency: callables

In FastAPI, a dependency must be a callable. A callable in Python is anything that can be executed like a function, such as a function itself, a class, or any object with a __call__ method. FastAPI checks that the dependency is a callable and analyzes its parameters in the same way as path operation function parameters, including sub-dependencies.

Class dependency syntax without Annotated

When using a class as a dependency without Annotated (Python 3.9 and earlier compatibility), use the syntax: commons: CommonQueryParams = Depends(CommonQueryParams). The Depends() call specifies what FastAPI will instantiate and inject. Prefer the Annotated version if possible.

Depends() shortcut for class dependencies

FastAPI provides a shortcut for class dependencies to reduce code repetition. Instead of writing commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)], you can write commons: Annotated[CommonQueryParams, Depends()] with Depends() having no parameters. FastAPI infers the class to instantiate from the type annotation. For non-Annotated syntax: commons: CommonQueryParams = Depends().

Type annotation purpose in class dependencies

When declaring a class dependency, the type annotation in the parameter declaration (such as CommonQueryParams) has no special meaning for FastAPI's data conversion or validation. It serves only to help your editor provide code completion, type checking, and other IDE support. FastAPI uses only the value passed to Depends() for actual dependency resolution.

Class dependency syntax with Annotated

When using a class as a dependency with Python 3.10+, use the syntax: commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]. The second CommonQueryParams inside Depends() is what FastAPI uses to extract parameters and call the dependency. The first CommonQueryParams in the type annotation helps your editor provide code completion and type checking, but is not used by FastAPI for data conversion or validation.

Class dependency example with CommonQueryParams

Example of using a class as a dependency with Annotated syntax (Python 3.10+): from typing import Annotated from fastapi import FastAPI, Depends class CommonQueryParams: def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100): self.q = q self.skip = skip self.limit = limit app = FastAPI() @app.get("/items/") async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]): return commons This creates a class with __init__ parameters that FastAPI will extract and validate. The class instance is passed to the path operation function.

Classes as dependencies in FastAPI

Python classes can be used as dependencies in FastAPI. When you pass a class as a dependency, FastAPI analyzes the parameters of its __init__ method and processes them the same way as path operation function parameters, including type conversion, validation, and OpenAPI documentation. FastAPI will instantiate the class and pass the instance to the path operation function.

Group dependencies for multiple path operations

Dependencies can be declared for a group of path operations when structuring bigger applications with multiple files. This allows setting shared dependencies for related endpoints without adding them individually to each path operation.

Global dependencies on FastAPI application

You can add dependencies to the whole FastAPI application by passing a dependencies parameter to the FastAPI constructor. These dependencies will be applied to all path operations in the application, similar to how you can add dependencies to individual path operation decorators.

Depends scope parameter for cleanup timing

The Depends() function accepts a scope parameter that controls when dependency exit code runs. Set scope='function' to run exit code after the path operation function returns but before the response is sent. Set scope='request' (the default for yield dependencies) to run exit code after the response is sent.

yield in dependencies for cleanup code

In FastAPI dependencies, use yield instead of return to execute cleanup code after the response is sent. Code before yield is executed before the response is created; the yielded value is injected into path operations and other dependencies; code after yield executes after the response is sent. Use yield only once per dependency.

Dependencies with yield can be async or sync

Both async and regular functions can use yield in FastAPI dependencies. FastAPI handles both types correctly, the same way as with normal dependencies.

try/except/finally with yield dependencies

When using a try block in a dependency with yield, any exception thrown during dependency usage or in path operations is received in the dependency. Use except to catch specific exceptions, and use finally to ensure exit steps run regardless of whether an exception occurred.

Sub-dependencies with yield execute in correct order

FastAPI ensures that exit code in each dependency with yield runs in the correct order when sub-dependencies are nested. For example, if dependency_c depends on dependency_b, which depends on dependency_a, FastAPI runs their exit code in reverse order (c then b then a) so each dependency's exit code can still access its dependencies' values.

Mixing yield and return dependencies

You can have some dependencies with yield and others with return in the same application, and they can depend on each other. FastAPI ensures everything runs in the correct order regardless of the mix.

HTTPException handling in yield dependencies

Dependencies with yield can catch exceptions using except blocks and raise HTTPException or other exceptions. This is an advanced technique; in most cases you should raise exceptions directly from path operation functions instead.

Swallowing exceptions in yield dependencies without logging

If you catch an exception with except in a yield dependency and do not raise it again, FastAPI will not be aware of the exception and the client will receive an HTTP 500 error, but the server will have no logs or indication of what the error was.

Always re-raise exceptions in yield dependencies

When catching an exception in a dependency with yield using except, you should always re-raise the exception unless you are raising a new HTTPException or similar. Use raise without arguments to re-raise the same exception, ensuring proper logging and error handling.

Scope constraints for sub-dependencies

When a dependency has scope='request', any sub-dependencies must also have scope='request'. However, a dependency with scope='function' can have sub-dependencies with either scope='function' or scope='request'. This is because a parent dependency needs its sub-dependencies' values available during its own exit code.

FastAPI creates context managers internally for yield dependencies

FastAPI internally uses Python's context managers (contextlib.contextmanager or asynccontextmanager decorators) to manage dependencies with yield. As a user, you do not need to use these decorators directly; FastAPI handles the wrapping automatically.

Using context managers with statements inside yield dependencies

You can use with or async with statements inside a dependency function with yield to work with context managers. The context manager will be entered before yield and exited after the cleanup code runs.

Database session example with yield dependency

A common use case for yield dependencies is creating a database session before a request and closing it after. Code before yield creates the session, the yield statement provides it to the path operation, and code after yield closes the session.

What is Dependency Injection

Dependency Injection means that path operation functions can declare things they require to work and use as dependencies. FastAPI then takes care of providing the code with those needed dependencies by injecting them. It is useful for having shared logic, sharing database connections, enforcing security and authentication, and minimizing code repetition.

Create a dependency function

A dependency is just a function that can take the same parameters that a path operation function can take. It has the same shape and structure as path operation functions but without the decorator. A dependency can return anything you want.

Import Depends from FastAPI

To use the dependency injection system, import Depends from fastapi.

Declare a dependency in a path operation function

Use Depends with a parameter in your path operation function the same way you use Body or Query. Pass Depends a single parameter which must be a function. Do not call the function directly (do not add parentheses at the end), just pass it as a parameter to Depends(). The function takes parameters the same way path operation functions do.

Dependencies can be async or sync

Dependencies follow the same rules as path operation functions. You can use async def or normal def. You can declare async def dependencies inside normal def path operation functions, or def dependencies inside async def path operation functions. FastAPI knows what to do in all cases.

Dependencies integrated in OpenAPI schema

All request declarations, validations and requirements of dependencies and sub-dependencies are integrated in the same OpenAPI schema. The interactive documentation will show all information from these dependencies.

Hierarchical dependency injection

Dependencies can define other dependencies themselves, creating a hierarchical tree of dependencies. The Dependency Injection system automatically solves all these dependencies and their sub-dependencies and provides the results at each step.

FastAPI Annotated support version requirement

FastAPI added support for Annotated and started recommending it in version 0.95.0. If you have an older version, you will get errors when trying to use Annotated. You should upgrade FastAPI to at least version 0.95.1 to use Annotated.

How FastAPI processes dependencies

Whenever a new request arrives, FastAPI calls the dependency function with the correct parameters, gets the result from that function, and assigns that result to the parameter in the path operation function.

Share dependencies with Annotated type aliases

When using Annotated, you can store an Annotated value containing Depends in a variable and use it in multiple places. This reduces code duplication while preserving type information, which allows editors to provide autocompletion, inline errors, and tools like mypy to work correctly.

Sub-dependencies allow dependencies to depend on other dependencies

FastAPI supports sub-dependencies, which are dependencies that themselves declare dependencies on other dependencies. These can be nested as deeply as needed, and FastAPI automatically resolves the dependency graph.

Same dependency called once per request by default (caching)

If a sub-dependency is declared multiple times for the same path operation, FastAPI calls it only once per request and caches the returned value. All dependants needing it receive the same cached value instead of the dependency being called multiple times.

use_cache=False parameter disables dependency caching

To force a dependency to be called every time instead of using the cached value, pass use_cache=False to the Depends() call. Example with Annotated: async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]). Without Annotated: async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)).

Dependency Injection pattern in FastAPI

FastAPI's Dependency Injection system uses regular functions that look the same as path operation functions. This pattern allows you to declare arbitrarily deeply nested dependency graphs and is particularly powerful when combined with security features.

FastAPI calls sub-dependencies before dependants

When a path operation declares a dependency that itself depends on another dependency, FastAPI automatically resolves the sub-dependency first and passes its returned value to the dependent function.

Nested dependencies in security

FastAPI allows nested dependencies, where a dependency can have its own sub-dependencies. For example, get_current_user can depend on oauth2_scheme, which provides a token that get_current_user then processes.

Create a Session dependency with yield

Create a FastAPI dependency with yield that provides a new Session for each request, ensuring a single session per request.

Give your agent this brain