From 44ff653664fa8fe773f86cfc57bd153bd70d8e33 Mon Sep 17 00:00:00 2001 From: JP-Ellis Date: Wed, 5 Mar 2025 19:04:57 +1100 Subject: [PATCH] docs: add caveat about ContextVar in dependencies As discovered and discussed in #13382, ContextVars set in a _synchronous_ dependency is not available to the rest of the request due to the way FastAPI handles that dependency. The documentation did not make any mention of this, and it was only after I asked that I discovered this was intended behaviour. So I am updating the docs to make this clear to others. Ref: #13382 Signed-off-by: JP-Ellis --- docs/en/docs/tutorial/dependencies/index.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index 596ce1599..2c19ffb86 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -156,6 +156,19 @@ If you don't know, check the [Async: *"In a hurry?"*](../../async.md#in-a-hurry) /// +/// warning + +**ContextVar Propagation** + +Python's [`ContextVar`](https://docs.python.org/3/library/contextvars.html) provides thread-safe shared storage as documented in [PEP 567](https://peps.python.org/pep-0567/). However, when using ContextVars with FastAPI dependencies, keep in mind: + +* `ContextVar` values set in synchronous (`def`) dependencies are **not** accessible in the rest of the request lifecycle as FastAPI executes them in isolated threads. +* To ensure `ContextVar` values are available throughout the request (including other dependencies, provided they run in the right order), use **asynchronous (`async def`) dependencies**. +* If you must use synchronous dependencies, prefer passing data explicitly or using [`Request.state`](https://fastapi.tiangolo.com/advanced/middleware/#using-the-request-object-in-a-middleware) for request-scoped storage. +* **Troubleshooting tip:** If a `ContextVar` value is unexpectedly `None` or missing, check whether it was set in a synchronous dependency. + +/// + ## Integrated with OpenAPI All the request declarations, validations and requirements of your dependencies (and sub-dependencies) will be integrated in the same OpenAPI schema.