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 · all subjects

dependency injection

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

Dependencies in decorators avoid unused parameter warnings

Using the `dependencies` parameter in the path operation decorator instead of declaring unused parameters in the function signature prevents editors from warning about unused function parameters and avoids confusing new developers who might see the unused parameter and think it is unnecessary.

Dependencies in decorators support all standard features

Dependencies declared in the `dependencies` parameter of a path operation decorator support all the same features as normal dependencies: they can declare request requirements (such as headers), raise exceptions, and return values (even though the returned values are not used).

Reusing dependencies in decorator parameter

You can reuse a normal dependency function that returns a value by placing it in the `dependencies` parameter of a path operation decorator. The dependency will be executed and validated even though its return value is not used by the path operation function.

Class __init__ parameters become dependency parameters

When you use a class as a dependency, the parameters defined in its __init__ method are treated as dependency parameters by FastAPI. These parameters are processed the same way as path operation function parameters, including type conversion, validation, and OpenAPI schema documentation.

Using classes without parameters as dependencies

FastAPI supports using callables without parameters as dependencies, whether they are functions or classes.

Why type annotations matter with Depends()

The type annotation in a dependency declaration (the first occurrence of the class name) does not affect FastAPI's data conversion or validation—FastAPI only uses Depends() for that. However, the type annotation helps your editor provide code completion, type checking, and other IDE support.

Dependencies for groups of path operations

When structuring larger applications with multiple files, you can declare a single `dependencies` parameter for a group of path operations, which is useful for organizing dependencies across related endpoints.

Disabling dependency caching with use_cache=False

To force a dependency to be called multiple times within the same request instead of using the cached value, set the parameter use_cache=False when using Depends(). Syntax: Depends(get_value, use_cache=False).

Dependency resolver graph structure

When a path operation declares a single dependency, FastAPI resolves nested sub-dependencies automatically. For example, if dependency B depends on dependency A, declaring only B in a path operation will cause FastAPI to first resolve A, pass its result to B, then pass B's result to the path operation function.

Dependency injection with Annotated

Dependencies can be declared using Annotated with Depends() for Python 3.10+. Example: async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]: return {"fresh_value": fresh_value}

Dependency injection without Annotated

Dependencies can also be declared without Annotated using the Depends() syntax in default parameter values. Example: async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): return {"fresh_value": fresh_value}

Dependency resolution as dependency graph

FastAPI's dependency injection system allows declaration of arbitrarily deeply nested dependency graphs (trees). Dependencies are resolved as a graph structure where each dependency can have its own sub-dependencies.

Exception propagation in yield dependencies

If code in a path operation function raises any exception (including HTTPException), it is passed to dependencies with yield. In most cases, you should re-raise the same exception or a new one from the dependency with yield to ensure it is handled correctly.

HTTPException in yield dependencies

You can raise HTTPException in a dependency with yield to create custom responses. You can catch exceptions with `except` and raise a new HTTPException or other exception in response. This is an advanced technique that is usually not needed since exceptions can be raised in the path operation function directly.

Depends scope parameter

The `Depends()` function accepts a `scope` parameter with two possible values: 'function' or 'request'. The 'function' scope starts the dependency before the path operation function and ends it after the function returns, but before the response is sent to the client. The 'request' scope starts the dependency before the path operation function and ends it after the response is sent to the client. If not specified and the dependency has yield, the default scope is 'request'.

Execution order of dependencies with yield

When a client makes a request, dependencies with yield execute their setup code in order. If an exception is raised during setup or in the path operation, it is passed to the exception handler and an HTTP error response is sent. If no exception occurs, the path operation executes and sends a response to the client. After the response is sent (for scope='request') or before it is sent (for scope='function'), background tasks execute. Finally, dependencies with yield execute their cleanup code in reverse order (innermost dependencies first).

Only one yield per dependency

Each dependency function should use `yield` only once.

Scope early exit - response already sent

Normally, the exit code of dependencies with yield executes after the response is sent to the client. Only one response can be sent to the client. After a response is sent, it cannot be changed or another response sent. If you declare scope='function', the exit code runs before the response is sent, allowing you to still modify state before response delivery.

Context managers in yield dependencies

You can use Python context managers within FastAPI dependencies with yield by using `with` or `async with` statements inside the dependency function. You can create context managers by defining a class with `__enter__()` and `__exit__()` methods, or by using `@contextlib.contextmanager` or `@contextlib.asynccontextmanager` decorators. You do not need to apply these decorators yourself for FastAPI dependencies since FastAPI handles this internally.

What makes a dependency callable

A dependency in FastAPI must be a 'callable'. A callable in Python is anything that can be executed like a function, including functions, classes, or any object that implements the __call__ method. FastAPI will analyze the parameters of any callable (function, class, or other) and process them the same way as path operation function parameters, including sub-dependencies.

Classes as dependencies

Python classes can be used as dependencies in FastAPI. When you pass a class as a dependency, FastAPI will call that class (instantiate it) and pass the instance to the path operation function. FastAPI analyzes the __init__ method's parameters and processes them just like path operation function parameters, extracting query parameters, validating them, and documenting them in the OpenAPI schema.

Type annotation with Depends() for class dependencies

When using a class as a dependency, you declare it with a type annotation and Depends(). In Python 3.10+ with Annotated, write: `commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]`. Without Annotated: `commons: CommonQueryParams = Depends(CommonQueryParams)`. The first reference is for editor support and type checking. The reference inside Depends() is what FastAPI uses to extract parameters and call the dependency. The type annotation is encouraged because editors can provide code completion and type checking on the instance.

Depends() shortcut for class dependencies

FastAPI provides a shortcut when the dependency is specifically a class. Instead of writing `commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]`, you can write `commons: Annotated[CommonQueryParams, Depends()]` in Python 3.10+. Without Annotated: `commons: CommonQueryParams = Depends()`. FastAPI infers the dependency from the type annotation, avoiding code repetition. This shortcut only works when the dependency is a class that FastAPI will call to create an instance.

Type annotation vs Depends distinction

In `commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]`, the first CommonQueryParams (in the type annotation) has no special meaning for FastAPI regarding data conversion or validation. It is used only for editor support and type checking. The CommonQueryParams inside Depends() is what FastAPI actually uses to extract declared parameters, perform validation, and convert data. You could technically use `Annotated[Any, Depends(CommonQueryParams)]` and FastAPI would process it the same way, but declaring the correct type helps editors provide better support.

Class dependency example with query parameters

A class used as a dependency can have an __init__ method with typed parameters that become query parameters. FastAPI will extract and validate these parameters from the request. Example: a CommonQueryParams class with __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100) becomes query parameters q, skip (default 0), and limit (default 100), with data conversion and validation applied.

Path operation decorator dependencies use case

Use dependencies in the path operation decorator 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 also helps avoid editor warnings about unused function parameters.

Dependencies in decorators can raise exceptions

Dependencies declared in the path operation decorator via the `dependencies` argument can raise exceptions the same as normal dependencies.

Dependencies in decorators execute regardless of return value

Dependencies in the path operation decorator's `dependencies` list will be executed whether they return values or not. You can reuse normal dependencies that return values even though the values won't be used by the path operation function.

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/solved the same way as normal dependencies, but their return values (if any) won't be passed to the path operation function.

Dependencies in decorators can declare request requirements

Dependencies added to the path operation decorator via the `dependencies` argument can declare request requirements such as headers or other sub-dependencies, just like normal dependencies.

Global dependencies use same syntax as path operation dependencies

The same ideas and syntax used for adding dependencies to individual path operation decorators apply when adding dependencies globally to the FastAPI application. All concepts from path operation dependencies carry over to the global scope.

Group dependencies across multiple path operations

Dependencies can be declared for a group of path operations (rather than globally or individually) when structuring bigger applications with multiple files. This allows organizing dependencies at an intermediate level between global and per-operation scope.

Global dependencies applied to all path operations

You can add dependencies to the FastAPI application instance itself by passing a dependencies parameter. When dependencies are added to the FastAPI application, they will be applied to all path operations in the application.

FastAPI resolves nested dependencies in correct order

When a path operation declares a dependency that itself has sub-dependencies, FastAPI automatically resolves the sub-dependencies first before calling the parent dependency. The resolution follows the dependency graph, with deeper dependencies being resolved before they are passed to their dependants.

Disable dependency caching with use_cache parameter

To make FastAPI call a dependency at every step instead of using the cached value, pass use_cache=False to the Depends() call. Example: Depends(get_value, use_cache=False). This works both with Annotated syntax and with plain function parameter syntax.

Dependency injection example with use_cache=False

Example using Annotated syntax: async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): return {"fresh_value": fresh_value}. Example without Annotated: async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): return {"fresh_value": fresh_value}

Dependencies can be both dependable and dependant

A function can be both a dependency (a 'dependable' that provides a value to other functions) and itself declare dependencies (be a 'dependant' that depends on other dependencies). This allows building chains and graphs of dependencies.

Sub-dependencies can be nested arbitrarily deep

FastAPI allows you to create dependencies that have sub-dependencies, and these can be nested as deeply as needed. FastAPI will automatically resolve the entire dependency graph.

Dependency caching within a single request

If the same dependency is declared multiple times for a path operation (for example, as a sub-dependency of multiple dependencies), FastAPI will call that dependency only once per request and cache the returned value. It will pass the cached value to all dependants that need it, instead of calling the dependency multiple times.

Context managers with yield in dependencies

You can use context managers (objects with `__enter__()` and `__exit__()` methods) inside FastAPI dependencies with `yield` by using `with` or `async with` statements within the dependency function. FastAPI will manage them internally.

Dependencies with yield instead of return

FastAPI supports dependencies that use `yield` instead of `return` to perform cleanup code after the response is sent. Code before `yield` executes before the response, the yielded value is injected into path operations or other dependencies, and code after `yield` executes after the response.

Use yield one single time per dependency

When using dependencies with `yield` in FastAPI, ensure that `yield` appears exactly one single time in each dependency function.

FastAPI dependencies with yield use contextlib internally

FastAPI uses `@contextlib.contextmanager` or `@contextlib.asynccontextmanager` decorators internally for dependencies with `yield`. Any function valid for these decorators is valid as a FastAPI dependency.

Try-except blocks in yield dependencies catch exceptions

If you use a `try` block in a dependency with `yield`, any exception thrown during the path operation or other dependencies will be received in the dependency. This allows catching specific exceptions with `except` and using `finally` to ensure exit code runs regardless of exceptions.

Nested dependencies with yield execute in correct order

FastAPI ensures that the exit code in each dependency with `yield` runs in the correct order for nested dependencies. If dependency_c depends on dependency_b which depends on dependency_a, all using `yield`, FastAPI executes exit code in reverse order so each dependency's exit code can still use its sub-dependencies' values.

Re-raise exceptions in yield dependencies without HTTPException

If you catch an exception using `except` in a dependency with `yield` and do not raise another `HTTPException` or similar exception, FastAPI will not be able to track the error and the client will see HTTP 500, but the server will have no logs of what happened. Always re-raise the original exception or raise a new one unless you are raising an `HTTPException`.

Depends scope parameter controls cleanup timing

The `Depends()` function accepts a `scope` parameter that controls when a dependency with `yield` is closed. The value `"function"` closes the dependency after the path operation function returns but before the response is sent. The value `"request"` closes the dependency after the response is sent to the client. If not specified and the dependency has `yield`, the default scope is `"request"`.

Sub-dependency scope requirements

When a dependency has `scope="request"` (the default), any sub-dependency 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 dependency needs to run its exit code before its sub-dependencies exit, so it can still use them during cleanup.

Dependency exit code executes after response by default

By default, the exit code (code after `yield`) in a dependency is executed after the response has been sent to the client. This can be changed using `Depends(scope="function")` to close the dependency before the response is sent.

Only one response sent to client with yield dependencies

When using dependencies with `yield`, only one response is sent to the client. It is either an error response (if an exception was caught by an exception handler) or the response from the path operation. After a response is sent, no other response can be sent.

Execution sequence for dependencies with yield

The execution sequence for dependencies with `yield` is: (1) code before `yield` runs before the response, (2) if an exception is raised in code before `yield`, it goes to the exception handler and returns an HTTP error response to the client, (3) the dependency is passed to the path operation, (4) if the path operation raises an exception, it is passed to the dependency with `yield`, which can catch and handle it, (5) the response is sent to the client, (6) background tasks are executed, (7) code after `yield` runs in cleanup (after response is sent to client unless using `scope="function"`).

Dependency composition for authentication state

Create additional dependencies that use other dependencies internally. For example, create get_current_active_user that depends on get_current_user, to check multiple conditions (user existence, authentication, active status). Dependencies will return HTTP errors if conditions are not met, ensuring endpoints only receive valid users.

Give your agent this brain