fastapi-injected 0.4.2__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/PKG-INFO +124 -12
  2. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/README.md +123 -11
  3. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/__init__.py +14 -1
  4. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_bind.py +24 -1
  5. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_deps_tp.py +15 -1
  6. fastapi_injected-0.5.0/fastapi_injected/_not_none.py +63 -0
  7. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/ctx.py +162 -25
  8. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/deps.py +2 -1
  9. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/ext.py +18 -2
  10. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/fastapi.py +77 -14
  11. fastapi_injected-0.5.0/fastapi_injected/openapi.py +125 -0
  12. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/overrides.py +4 -5
  13. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/reflect/_routes.py +24 -11
  14. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/signature.py +47 -5
  15. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/pyproject.toml +1 -1
  16. fastapi_injected-0.5.0/tests/conftest.py +12 -0
  17. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_bind.py +69 -3
  18. fastapi_injected-0.5.0/tests/test_context_value.py +85 -0
  19. fastapi_injected-0.5.0/tests/test_default_app.py +76 -0
  20. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_fastapi.py +122 -4
  21. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_injected.py +11 -1
  22. fastapi_injected-0.5.0/tests/test_not_none.py +88 -0
  23. fastapi_injected-0.5.0/tests/test_openapi.py +133 -0
  24. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_overrides.py +73 -1
  25. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_reflect.py +63 -2
  26. fastapi_injected-0.5.0/tests/test_signature.py +107 -0
  27. fastapi_injected-0.5.0/tests/test_type_checking_aliases.py +43 -0
  28. fastapi_injected-0.5.0/uv.lock +857 -0
  29. fastapi_injected-0.4.2/uv.lock +0 -839
  30. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.github/dependabot.yml +0 -0
  31. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.github/workflows/automerge.yml +0 -0
  32. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.github/workflows/lint.yml +0 -0
  33. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.github/workflows/publish.yml +0 -0
  34. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.github/workflows/test.yml +0 -0
  35. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.gitignore +0 -0
  36. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/.pre-commit-config.yaml +0 -0
  37. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/LICENSE +0 -0
  38. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_body.py +0 -0
  39. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_cache.py +0 -0
  40. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_calls.py +0 -0
  41. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_dataclass.py +0 -0
  42. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_given.py +0 -0
  43. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_injected.py +0 -0
  44. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_overrides.py +0 -0
  45. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/_rlock.py +0 -0
  46. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/inject.py +0 -0
  47. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/reflect/__init__.py +0 -0
  48. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/reflect/_dependant.py +0 -0
  49. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/reflect/_openapi.py +0 -0
  50. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/resolve.py +0 -0
  51. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/fastapi_injected/types.py +0 -0
  52. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/__init__.py +0 -0
  53. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/__init__.py +0 -0
  54. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/annotations.py +0 -0
  55. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/arg.py +0 -0
  56. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/bind.py +0 -0
  57. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/ctx.py +0 -0
  58. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/dataclass.py +0 -0
  59. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/deps.py +0 -0
  60. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/errors.py +0 -0
  61. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/given.py +0 -0
  62. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/inject.py +0 -0
  63. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/injected.py +0 -0
  64. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/integration.py +0 -0
  65. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/markers.py +0 -0
  66. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/overrides.py +0 -0
  67. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/_typing/resolve.py +0 -0
  68. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/deps.py +0 -0
  69. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/ext/__init__.py +0 -0
  70. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/ext/test_pydantic_ai.py +0 -0
  71. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_body.py +0 -0
  72. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_body_reads.py +0 -0
  73. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_cache.py +0 -0
  74. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_calls.py +0 -0
  75. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_concurrency.py +0 -0
  76. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_ctx.py +0 -0
  77. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_dataclass.py +0 -0
  78. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_dependant_cache.py +0 -0
  79. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_errors.py +0 -0
  80. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_given.py +0 -0
  81. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_inject.py +0 -0
  82. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_request_params.py +0 -0
  83. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_resolve.py +0 -0
  84. {fastapi_injected-0.4.2 → fastapi_injected-0.5.0}/tests/test_rlock.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: fastapi-injected
3
- Version: 0.4.2
3
+ Version: 0.5.0
4
4
  Summary: Yet another library to reuse fastapi dependency injection
5
5
  Project-URL: Repository, https://github.com/uriyyo/fastapi-injected
6
6
  Author-email: Yurii Karabas <1998uriyyo@gmail.com>
@@ -163,7 +163,7 @@ async with injection_ctx(app=app):
163
163
  await handler() # `request.app.state` resolves as it does in a route
164
164
  ```
165
165
 
166
- Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
166
+ Without it, the context falls back to the default app — the last one given to `add_injection` (see [FastAPI request integration](#fastapi-request-integration)). With neither, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
167
167
 
168
168
  When a dependency reads more of the request than that — a header, a cookie, a query or path parameter, the body — describe the request with `synthetic_request` and hand it to the context:
169
169
 
@@ -185,6 +185,27 @@ async with injection_ctx(request=request):
185
185
 
186
186
  Analysing a dependency is the expensive part of resolving one, so the result is cached — keyed by the dependency itself, not by whatever object carried it, so nothing that only passed through is kept alive. Only dependencies written in source code are cached this way: functions and classes, and annotations built from them. One made at runtime — `Given(...)`, a `MakeInjected` or `bind_deps` result, an object that brings its own `Depends` — is analysed again on every resolve, and FastAPI never gets to keep it: what it carries is released with the resolve instead of living as long as the process. `clear_dependant_cache()` drops the cache, for long-lived processes and test suites that want the memory back.
187
187
 
188
+ ### Values scoped to a context
189
+
190
+ `ContextValue` is a `ContextVar` that lives as long as an injection context - inside a route, as long as the request. `set` writes to the current context, `get` reads the nearest one that has it: a nested context sees the value, but what it sets stays in it.
191
+
192
+ ```python
193
+ from fastapi_injected import ContextValue
194
+
195
+ tenant = ContextValue[str]("tenant", default="public")
196
+
197
+
198
+ def set_tenant(x_tenant: Annotated[str, Header()]) -> None:
199
+ tenant.set(x_tenant)
200
+
201
+
202
+ @app.get("/", dependencies=[Depends(set_tenant)])
203
+ async def route() -> str:
204
+ return tenant.get() # this request's tenant
205
+ ```
206
+
207
+ Without a default, `get` raises `LookupError` when nothing set it; `set` outside a context raises `NoInjectionContextError`.
208
+
188
209
  ### Overriding dependencies
189
210
 
190
211
  `push_overrides` swaps dependencies out for the duration of a `with` block — handy in tests, or anywhere you need to run the same code against a different implementation:
@@ -222,7 +243,22 @@ with push_overrides(
222
243
 
223
244
  Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested `push_overrides` blocks merge, with the innermost one winning.
224
245
 
225
- An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override:
246
+ An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override.
247
+
248
+ Enter the block with `async with` for what it builds to be torn down when the block ends. A plain `with` cannot run async teardown, so generator dependencies first built inside it are torn down with the surrounding context instead:
249
+
250
+ ```python
251
+ async with injection_ctx():
252
+ async with push_overrides({Session: fake}):
253
+ await handler() # a generator dependency built here...
254
+ # ...is torn down here
255
+
256
+ with push_overrides({Session: fake}):
257
+ await handler()
258
+ # still open - torn down when `injection_ctx()` ends
259
+ ```
260
+
261
+ Reuse of the surrounding cache works the same either way:
226
262
 
227
263
  ```python
228
264
  async with injection_ctx():
@@ -246,6 +282,8 @@ async with injection_ctx({Session: fake}) as ctx:
246
282
 
247
283
  For FastAPI's own `app.dependency_overrides`, `override_app(app, {dep: fake})` sets entries for a `with` block and restores the previous mapping afterwards, including entries added inside the block.
248
284
 
285
+ A route reads `app.dependency_overrides` on its own. Outside a request, a context only knows the application it is given: `injection_ctx(app=app)`, or a `request=` whose scope carries one, applies that app's overrides the way a route would, beneath the overrides passed to the context itself. A context given neither uses the default app, the last one given to `add_injection`, and applies none when there is no default.
286
+
249
287
  ### Dependencies that are objects
250
288
 
251
289
  Resolved values are cached in their context by the callable that resolves them, so a dependency that is an object — a class holding configuration, a parametrized resolver — has to be hashable to get there. A plain dataclass is not, and a frozen one still refuses as soon as it holds a list or a dict.
@@ -291,6 +329,28 @@ except DependencyResolutionError as exc:
291
329
 
292
330
  It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
293
331
 
332
+ ### Values that must be there
333
+
334
+ A dependency that loads something often returns `None` when it is missing. `NotNone[T, dep]` is what `dep` resolves to, or a 404 when that is `None`, and a type checker sees it as plain `T`:
335
+
336
+ ```python
337
+ from typing import Annotated
338
+ from fastapi import Depends
339
+ from fastapi_injected import NotNone
340
+
341
+ type MaybeUserDep = Annotated[User | None, Depends(load_user)]
342
+ type UserDep = NotNone[User, MaybeUserDep]
343
+
344
+
345
+ @app.get("/users/{user_id}")
346
+ async def get_user(user: UserDep) -> User:
347
+ return user # never None here
348
+ ```
349
+
350
+ A third item chooses the error: anything called with no arguments that returns an exception, such as an exception class — `NotNone[User, MaybeUserDep, UserGone]`.
351
+
352
+ `NotNone` reads the same dependency it wraps, so a handler can ask for `UserDep` and `MaybeUserDep` side by side and the user is still loaded once per request. A dependency made at runtime, like `Given(...)`, works too, and is not kept once its resolve is done.
353
+
294
354
  ### Dependencies decided at runtime
295
355
 
296
356
  A dependency is usually written as an annotation, but sometimes it is a value a caller already has, or one picked while the program runs. `Given` turns a value into a dependency that resolves to it:
@@ -323,6 +383,8 @@ What a parameter is bound to can be written any way a dependency can be: a marke
323
383
 
324
384
  Binding takes the parameters away, and a type checker sees what is left: `bind_deps(describe, Given(doc))` is a function of `(role)`, and binding both leaves one of no arguments at all. The bound function is a dependency like any other — resolve it, `@inject` it, override what it depends on. Binding more markers than the function has parameters is a `TypeError` rather than a silent truncation.
325
385
 
386
+ A request marker is bound under a made-up parameter name, so it has to say what it reads: `Annotated[int, Path(alias="item_id")]` binds, while a bare `Path()`, `Query()`, `Header()` or `Cookie()` raises `UnnamedParamError` instead of reading a parameter no request carries.
387
+
326
388
  ### Dependencies as objects
327
389
 
328
390
  When the markers belong together, `MakeInjected` makes a dataclass of them: fields annotated with `DepOf` hold the markers, and the call receives what they resolve to.
@@ -345,8 +407,25 @@ class IsOwner(MakeInjected):
345
407
  await resolve(IsOwner(doc=Given(doc), role=RoleDep))
346
408
  ```
347
409
 
410
+ The call has to be an `async def`; a sync one raises `NotAsyncError`, as it does for `bind_deps` and `remap_dep_args`.
411
+
348
412
  It is a `MakeDataclass`, so instances built from equal markers are equal — and therefore one dependency, resolved once per context and overridable as a whole. For callables that are not dataclasses, the two halves of the binding are available on their own: `signature_with_deps(func, deps)` builds the signature, and `remap_dep_args` turns the arguments it names back into positional ones.
349
413
 
414
+ ### Objects that bring their own `Depends`
415
+
416
+ An object with a `__get_depends__()` method is resolved through the `Depends` it returns instead of its own call - by `resolve`, `as_depends`, `add_route_dependency` and `reflect`. The protocol is `fastapi_injected.types.HasDependsHook`:
417
+
418
+ ```python
419
+ class Guarded:
420
+ def __call__(self) -> None: ...
421
+
422
+ def __get_depends__(self) -> params.Depends:
423
+ return Depends(require_admin, use_cache=False)
424
+
425
+
426
+ await resolve(Guarded()) # resolves `require_admin`
427
+ ```
428
+
350
429
  ### Inspecting annotations
351
430
 
352
431
  `fastapi_injected.ext` holds a few helpers for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
@@ -354,6 +433,10 @@ It is a `MakeDataclass`, so instances built from equal markers are equal — and
354
433
  - `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
355
434
  - `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
356
435
  - `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
436
+ - `is_request_param(tp)` — whether `tp` carries `Header()`, `Query()`, `Path()`, `Cookie()` or a body marker.
437
+ - `unwrap_tp(tp)` — the value of a PEP 695 `type` alias, through nested aliases.
438
+ - `annotated(tp, *metadata)` — `Annotated[tp, *metadata]` without typing's cache, which would keep runtime markers alive.
439
+ - `as_depends(dep)` — the `Depends` for a marker, a `__get_depends__` object or a callable (`DependsSource`).
357
440
 
358
441
  ### Reflecting on apps and dependency trees
359
442
 
@@ -384,21 +467,34 @@ assert list(iter_security(route.dependant)) == [(bearer, ["items:write"])]
384
467
  - `match_route(app, request_or_scope)` — `(path_template, route)` for the route that would handle a request, through mounts, hosts and included routers; `None` when nothing matches. Useful in middleware, where `request.scope["route"]` is not set yet.
385
468
  - `iter_params(root)` — `(dependant, kind, field)` for every path, query, header, cookie and body parameter in the tree.
386
469
  - `response_type(route, *, strip=True)` — the route's response type, falling back to the endpoint's return annotation, with `Annotated` and `| None` stripped unless `strip=False`.
387
- - `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function.
470
+ - `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function. `globalns=`/`localns=` add names its annotations need beyond the module of `func`, and `include_return=True` keeps the return annotation.
388
471
  - `.add(*parameters)` — extra keyword-only parameters before `**kwargs`; names already present are kept as they are.
389
472
  - `.drop(*names)` and `.update(name, **changes)` — drop parameters a wrapper consumes itself, or change one parameter's annotation, default or kind.
390
473
  - `.add_dep(name, dep, *, annotation=Any)` — a parameter FastAPI resolves with a `Depends`/`Security` marker or a callable.
391
474
  - `.prepend(*parameters)`, `.rename(old, new)` and `.returns(annotation)` — positional parameters at the front, a renamed parameter, a new return annotation.
392
475
  - `Signature.role(parameter)` — which `ParamRole` a parameter plays: `dep` for `Dep[...]` or a `Depends` default, `request` for `Header()`/`Query()`/..., `arg` for `Arg[...]`, `plain` otherwise. `.select(*roles)` yields the parameters with those roles; `.annotations` and `.defaults` are name-to-value mappings of what is declared.
393
476
  - `.wrap(func)` — a forwarder to `func`, async when `func` is, carrying this signature; `.apply(func)` sets the signature on `func` itself.
394
- - `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
477
+ - `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` or `APIWebSocketRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
395
478
  - `add_lifespan(app_or_router, lifespan)` — run a lifespan inside the one already set, merging the state both yield, for libraries that need a startup step on an app they did not create.
396
479
 
397
480
  `root` for the dependency helpers is a `Dependant`, a `Depends(...)` marker or a plain callable; `as_dependant` is the conversion they share. A plain callable is read the way FastAPI would, with `Injected` defaults treated as dependencies.
398
481
 
482
+ ### Adding to the OpenAPI schema
483
+
484
+ `fastapi_injected.openapi` gives libraries one shared `app.openapi` to add to, instead of each replacing it. The schema is cached in `app.openapi_schema` until `invalidate_openapi(app)`.
485
+
486
+ - `add_openapi_hook(app, hook)` — `hook(app, schema)` post-processes the schema, in the order hooks were added; it changes `schema` in place or returns a new one.
487
+ - `__doc_depends__(methods)` — dependencies a call resolves itself, documented for every route that has it anywhere in its dependency tree (`HasDocDepends`, `iter_doc_depends(route)`). `add_openapi(app)` enables it without a hook.
488
+
489
+ A custom `app.openapi` is kept, and hooks run on its result.
490
+
491
+ ```python
492
+ add_openapi_hook(app, lambda app, schema: {**schema, "x-version": "1"})
493
+ ```
494
+
399
495
  ### FastAPI request integration
400
496
 
401
- Inside a FastAPI app, `@inject`-ed functions and `resolve` can share the request's own dependency cache — the same instances FastAPI built for the handler. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request, and the `bind_injection_ctx` dependency, which binds it to the connection of the route. Add it after your other middleware, so the context is open for them too:
497
+ Inside a FastAPI app, `@inject`-ed functions and `resolve` can share the request's own dependency cache — the same instances FastAPI built for the handler. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request and binds it to the route's connection once the route is found - before or after routers are included. FastAPI is patched by `add_injection` or `InjectionMiddleware`, not on import. Add it after your other middleware, so the context is open for them too:
402
498
 
403
499
  ```python
404
500
  from fastapi import FastAPI
@@ -414,6 +510,21 @@ async def route(service: Dep[Service]) -> str:
414
510
  ...
415
511
  ```
416
512
 
513
+ `add_injection` also makes `app` the default app: a context opened without a request — a background job, a bot handler, a script — resolves against it, so `request.app` is that app and its `dependency_overrides` apply, as they would in a route. The last app given to `add_injection` wins. `set_default_app` sets it directly, and used with `with` puts the previous one back when the block ends:
514
+
515
+ ```python
516
+ from fastapi_injected import set_default_app
517
+
518
+ set_default_app(worker_app) # for the rest of the process
519
+
520
+ with set_default_app(test_app): # only inside the block
521
+ await job()
522
+ ```
523
+
524
+ A `resolve()` failing inside a route answers with a 422, or closes a websocket: `add_injection` registers `dependency_resolution_handler` unless a handler for `DependencyResolutionError` exists or `handle_resolution_errors=False` is passed.
525
+
526
+ The default lives in a context variable, so it reaches the tasks started after it is set: set it at startup, not inside a task that other tasks will not see.
527
+
417
528
  Anything called from the handler — including `@inject`-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request. The context is opened by a middleware, so `resolve` also works inside middleware added before it (before routing, `request.scope["route"]` and path params are not available yet).
418
529
 
419
530
  WebSocket routes work the same way: the context is bound to the `WebSocket` instead of a `Request`, and dependencies that ask for one get it. A websocket handed to a dependency shares its handshake with the one the route received, so it can be talked through after the route has called `accept()`:
@@ -471,20 +582,21 @@ The root package is what you need to use the library, and the surface a release
471
582
  | | |
472
583
  | --- | --- |
473
584
  | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
474
- | Resolving | `inject`, `resolve`, `bind_deps` |
475
- | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
585
+ | Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
586
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `ContextValue`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
476
587
  | FastAPI integration | `add_injection` |
477
- | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
588
+ | Errors | `DependencyResolutionError`, `NoInjectionContextError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
478
589
 
479
590
  Code that builds on the library imports from the submodule that owns the piece. These are public too:
480
591
 
481
592
  | Module | Names |
482
593
  | --- | --- |
483
- | `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `strip_annotation`, `as_depends`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `UnboundDepArgsError` |
594
+ | `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `is_request_param`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `unwrap_tp`, `strip_annotation`, `annotated`, `as_depends`, `DependsSource`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `NotAsyncError`, `UnboundDepArgsError` |
484
595
  | `fastapi_injected.types` | `DepOf`, `ArgMarker`, `HasDependsHook`, and the typing vocabulary the signatures are written in — `DepReturn`, `DepShape`, `DepDecl`, `AsyncFunc`, `Coro`, `BoundConnection`, `DependencyCache` and friends |
485
- | `fastapi_injected.overrides` | `Overrides`, `OverridesProvider` |
596
+ | `fastapi_injected.overrides` | `Overrides`, `OverridesProvider`, `OverrideBlock` |
486
597
  | `fastapi_injected.signature` | `Signature`, `ParamRole` |
487
- | `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `MissingDependencyCacheError` |
598
+ | `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `dependency_resolution_handler`, `install_dependency_cache`, `MissingDependencyCacheError` |
599
+ | `fastapi_injected.openapi` | `add_openapi_hook`, `add_openapi`, `invalidate_openapi`, `HasDocDepends`, `iter_doc_depends`, `OpenAPIHook` |
488
600
  | `fastapi_injected.reflect` | `iter_dependant`, `iter_calls`, `iter_security`, `iter_params`, `find_dependant`, `iter_overridden`, `iter_routes`, `iter_api_routes`, `iter_routes_where`, `find_route`, `match_route`, `iter_routers`, `response_type`, `add_route_dependency`, `add_lifespan`, `iter_operations`, `operation_for`, `as_dependant` |
489
601
 
490
602
  Anything else, including every module whose name starts with an underscore, is machinery that can change in a patch release.
@@ -141,7 +141,7 @@ async with injection_ctx(app=app):
141
141
  await handler() # `request.app.state` resolves as it does in a route
142
142
  ```
143
143
 
144
- Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
144
+ Without it, the context falls back to the default app — the last one given to `add_injection` (see [FastAPI request integration](#fastapi-request-integration)). With neither, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
145
145
 
146
146
  When a dependency reads more of the request than that — a header, a cookie, a query or path parameter, the body — describe the request with `synthetic_request` and hand it to the context:
147
147
 
@@ -163,6 +163,27 @@ async with injection_ctx(request=request):
163
163
 
164
164
  Analysing a dependency is the expensive part of resolving one, so the result is cached — keyed by the dependency itself, not by whatever object carried it, so nothing that only passed through is kept alive. Only dependencies written in source code are cached this way: functions and classes, and annotations built from them. One made at runtime — `Given(...)`, a `MakeInjected` or `bind_deps` result, an object that brings its own `Depends` — is analysed again on every resolve, and FastAPI never gets to keep it: what it carries is released with the resolve instead of living as long as the process. `clear_dependant_cache()` drops the cache, for long-lived processes and test suites that want the memory back.
165
165
 
166
+ ### Values scoped to a context
167
+
168
+ `ContextValue` is a `ContextVar` that lives as long as an injection context - inside a route, as long as the request. `set` writes to the current context, `get` reads the nearest one that has it: a nested context sees the value, but what it sets stays in it.
169
+
170
+ ```python
171
+ from fastapi_injected import ContextValue
172
+
173
+ tenant = ContextValue[str]("tenant", default="public")
174
+
175
+
176
+ def set_tenant(x_tenant: Annotated[str, Header()]) -> None:
177
+ tenant.set(x_tenant)
178
+
179
+
180
+ @app.get("/", dependencies=[Depends(set_tenant)])
181
+ async def route() -> str:
182
+ return tenant.get() # this request's tenant
183
+ ```
184
+
185
+ Without a default, `get` raises `LookupError` when nothing set it; `set` outside a context raises `NoInjectionContextError`.
186
+
166
187
  ### Overriding dependencies
167
188
 
168
189
  `push_overrides` swaps dependencies out for the duration of a `with` block — handy in tests, or anywhere you need to run the same code against a different implementation:
@@ -200,7 +221,22 @@ with push_overrides(
200
221
 
201
222
  Overrides apply to the whole graph, not just top-level parameters — overriding a nested dependency changes what its dependents receive. Nested `push_overrides` blocks merge, with the innermost one winning.
202
223
 
203
- An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override:
224
+ An override block is a context of its own: it caches what it builds, and that cache goes away with the block. The surrounding context keeps what it had resolved before, and it stays visible — except for the overridden dependencies and anything built from them, which are resolved again under the override.
225
+
226
+ Enter the block with `async with` for what it builds to be torn down when the block ends. A plain `with` cannot run async teardown, so generator dependencies first built inside it are torn down with the surrounding context instead:
227
+
228
+ ```python
229
+ async with injection_ctx():
230
+ async with push_overrides({Session: fake}):
231
+ await handler() # a generator dependency built here...
232
+ # ...is torn down here
233
+
234
+ with push_overrides({Session: fake}):
235
+ await handler()
236
+ # still open - torn down when `injection_ctx()` ends
237
+ ```
238
+
239
+ Reuse of the surrounding cache works the same either way:
204
240
 
205
241
  ```python
206
242
  async with injection_ctx():
@@ -224,6 +260,8 @@ async with injection_ctx({Session: fake}) as ctx:
224
260
 
225
261
  For FastAPI's own `app.dependency_overrides`, `override_app(app, {dep: fake})` sets entries for a `with` block and restores the previous mapping afterwards, including entries added inside the block.
226
262
 
263
+ A route reads `app.dependency_overrides` on its own. Outside a request, a context only knows the application it is given: `injection_ctx(app=app)`, or a `request=` whose scope carries one, applies that app's overrides the way a route would, beneath the overrides passed to the context itself. A context given neither uses the default app, the last one given to `add_injection`, and applies none when there is no default.
264
+
227
265
  ### Dependencies that are objects
228
266
 
229
267
  Resolved values are cached in their context by the callable that resolves them, so a dependency that is an object — a class holding configuration, a parametrized resolver — has to be hashable to get there. A plain dataclass is not, and a frozen one still refuses as soon as it holds a list or a dict.
@@ -269,6 +307,28 @@ except DependencyResolutionError as exc:
269
307
 
270
308
  It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
271
309
 
310
+ ### Values that must be there
311
+
312
+ A dependency that loads something often returns `None` when it is missing. `NotNone[T, dep]` is what `dep` resolves to, or a 404 when that is `None`, and a type checker sees it as plain `T`:
313
+
314
+ ```python
315
+ from typing import Annotated
316
+ from fastapi import Depends
317
+ from fastapi_injected import NotNone
318
+
319
+ type MaybeUserDep = Annotated[User | None, Depends(load_user)]
320
+ type UserDep = NotNone[User, MaybeUserDep]
321
+
322
+
323
+ @app.get("/users/{user_id}")
324
+ async def get_user(user: UserDep) -> User:
325
+ return user # never None here
326
+ ```
327
+
328
+ A third item chooses the error: anything called with no arguments that returns an exception, such as an exception class — `NotNone[User, MaybeUserDep, UserGone]`.
329
+
330
+ `NotNone` reads the same dependency it wraps, so a handler can ask for `UserDep` and `MaybeUserDep` side by side and the user is still loaded once per request. A dependency made at runtime, like `Given(...)`, works too, and is not kept once its resolve is done.
331
+
272
332
  ### Dependencies decided at runtime
273
333
 
274
334
  A dependency is usually written as an annotation, but sometimes it is a value a caller already has, or one picked while the program runs. `Given` turns a value into a dependency that resolves to it:
@@ -301,6 +361,8 @@ What a parameter is bound to can be written any way a dependency can be: a marke
301
361
 
302
362
  Binding takes the parameters away, and a type checker sees what is left: `bind_deps(describe, Given(doc))` is a function of `(role)`, and binding both leaves one of no arguments at all. The bound function is a dependency like any other — resolve it, `@inject` it, override what it depends on. Binding more markers than the function has parameters is a `TypeError` rather than a silent truncation.
303
363
 
364
+ A request marker is bound under a made-up parameter name, so it has to say what it reads: `Annotated[int, Path(alias="item_id")]` binds, while a bare `Path()`, `Query()`, `Header()` or `Cookie()` raises `UnnamedParamError` instead of reading a parameter no request carries.
365
+
304
366
  ### Dependencies as objects
305
367
 
306
368
  When the markers belong together, `MakeInjected` makes a dataclass of them: fields annotated with `DepOf` hold the markers, and the call receives what they resolve to.
@@ -323,8 +385,25 @@ class IsOwner(MakeInjected):
323
385
  await resolve(IsOwner(doc=Given(doc), role=RoleDep))
324
386
  ```
325
387
 
388
+ The call has to be an `async def`; a sync one raises `NotAsyncError`, as it does for `bind_deps` and `remap_dep_args`.
389
+
326
390
  It is a `MakeDataclass`, so instances built from equal markers are equal — and therefore one dependency, resolved once per context and overridable as a whole. For callables that are not dataclasses, the two halves of the binding are available on their own: `signature_with_deps(func, deps)` builds the signature, and `remap_dep_args` turns the arguments it names back into positional ones.
327
391
 
392
+ ### Objects that bring their own `Depends`
393
+
394
+ An object with a `__get_depends__()` method is resolved through the `Depends` it returns instead of its own call - by `resolve`, `as_depends`, `add_route_dependency` and `reflect`. The protocol is `fastapi_injected.types.HasDependsHook`:
395
+
396
+ ```python
397
+ class Guarded:
398
+ def __call__(self) -> None: ...
399
+
400
+ def __get_depends__(self) -> params.Depends:
401
+ return Depends(require_admin, use_cache=False)
402
+
403
+
404
+ await resolve(Guarded()) # resolves `require_admin`
405
+ ```
406
+
328
407
  ### Inspecting annotations
329
408
 
330
409
  `fastapi_injected.ext` holds a few helpers for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
@@ -332,6 +411,10 @@ It is a `MakeDataclass`, so instances built from equal markers are equal — and
332
411
  - `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
333
412
  - `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
334
413
  - `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
414
+ - `is_request_param(tp)` — whether `tp` carries `Header()`, `Query()`, `Path()`, `Cookie()` or a body marker.
415
+ - `unwrap_tp(tp)` — the value of a PEP 695 `type` alias, through nested aliases.
416
+ - `annotated(tp, *metadata)` — `Annotated[tp, *metadata]` without typing's cache, which would keep runtime markers alive.
417
+ - `as_depends(dep)` — the `Depends` for a marker, a `__get_depends__` object or a callable (`DependsSource`).
335
418
 
336
419
  ### Reflecting on apps and dependency trees
337
420
 
@@ -362,21 +445,34 @@ assert list(iter_security(route.dependant)) == [(bearer, ["items:write"])]
362
445
  - `match_route(app, request_or_scope)` — `(path_template, route)` for the route that would handle a request, through mounts, hosts and included routers; `None` when nothing matches. Useful in middleware, where `request.scope["route"]` is not set yet.
363
446
  - `iter_params(root)` — `(dependant, kind, field)` for every path, query, header, cookie and body parameter in the tree.
364
447
  - `response_type(route, *, strip=True)` — the route's response type, falling back to the endpoint's return annotation, with `Annotated` and `| None` stripped unless `strip=False`.
365
- - `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function.
448
+ - `Signature`, in `fastapi_injected.signature`, is an `inspect.Signature` with operations for decorators and dependencies that need FastAPI to see parameters a function did not declare. `Signature.of(func_or_signature)` starts one; each operation returns a new `Signature`, and `.apply(func)` sets it on a function. `globalns=`/`localns=` add names its annotations need beyond the module of `func`, and `include_return=True` keeps the return annotation.
366
449
  - `.add(*parameters)` — extra keyword-only parameters before `**kwargs`; names already present are kept as they are.
367
450
  - `.drop(*names)` and `.update(name, **changes)` — drop parameters a wrapper consumes itself, or change one parameter's annotation, default or kind.
368
451
  - `.add_dep(name, dep, *, annotation=Any)` — a parameter FastAPI resolves with a `Depends`/`Security` marker or a callable.
369
452
  - `.prepend(*parameters)`, `.rename(old, new)` and `.returns(annotation)` — positional parameters at the front, a renamed parameter, a new return annotation.
370
453
  - `Signature.role(parameter)` — which `ParamRole` a parameter plays: `dep` for `Dep[...]` or a `Depends` default, `request` for `Header()`/`Query()`/..., `arg` for `Arg[...]`, `plain` otherwise. `.select(*roles)` yields the parameters with those roles; `.annotations` and `.defaults` are name-to-value mappings of what is declared.
371
454
  - `.wrap(func)` — a forwarder to `func`, async when `func` is, carrying this signature; `.apply(func)` sets the signature on `func` itself.
372
- - `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
455
+ - `add_route_dependency(route, *deps)` — append dependencies to an `APIRoute` or `APIWebSocketRoute` that is already built, and rebuild what FastAPI derived from its dependencies. Call it before the route's router is included elsewhere: an included router keeps its own copy until its routes change.
373
456
  - `add_lifespan(app_or_router, lifespan)` — run a lifespan inside the one already set, merging the state both yield, for libraries that need a startup step on an app they did not create.
374
457
 
375
458
  `root` for the dependency helpers is a `Dependant`, a `Depends(...)` marker or a plain callable; `as_dependant` is the conversion they share. A plain callable is read the way FastAPI would, with `Injected` defaults treated as dependencies.
376
459
 
460
+ ### Adding to the OpenAPI schema
461
+
462
+ `fastapi_injected.openapi` gives libraries one shared `app.openapi` to add to, instead of each replacing it. The schema is cached in `app.openapi_schema` until `invalidate_openapi(app)`.
463
+
464
+ - `add_openapi_hook(app, hook)` — `hook(app, schema)` post-processes the schema, in the order hooks were added; it changes `schema` in place or returns a new one.
465
+ - `__doc_depends__(methods)` — dependencies a call resolves itself, documented for every route that has it anywhere in its dependency tree (`HasDocDepends`, `iter_doc_depends(route)`). `add_openapi(app)` enables it without a hook.
466
+
467
+ A custom `app.openapi` is kept, and hooks run on its result.
468
+
469
+ ```python
470
+ add_openapi_hook(app, lambda app, schema: {**schema, "x-version": "1"})
471
+ ```
472
+
377
473
  ### FastAPI request integration
378
474
 
379
- Inside a FastAPI app, `@inject`-ed functions and `resolve` can share the request's own dependency cache — the same instances FastAPI built for the handler. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request, and the `bind_injection_ctx` dependency, which binds it to the connection of the route. Add it after your other middleware, so the context is open for them too:
475
+ Inside a FastAPI app, `@inject`-ed functions and `resolve` can share the request's own dependency cache — the same instances FastAPI built for the handler. Call `add_injection`: it adds `InjectionMiddleware`, which opens the context for the whole request and binds it to the route's connection once the route is found - before or after routers are included. FastAPI is patched by `add_injection` or `InjectionMiddleware`, not on import. Add it after your other middleware, so the context is open for them too:
380
476
 
381
477
  ```python
382
478
  from fastapi import FastAPI
@@ -392,6 +488,21 @@ async def route(service: Dep[Service]) -> str:
392
488
  ...
393
489
  ```
394
490
 
491
+ `add_injection` also makes `app` the default app: a context opened without a request — a background job, a bot handler, a script — resolves against it, so `request.app` is that app and its `dependency_overrides` apply, as they would in a route. The last app given to `add_injection` wins. `set_default_app` sets it directly, and used with `with` puts the previous one back when the block ends:
492
+
493
+ ```python
494
+ from fastapi_injected import set_default_app
495
+
496
+ set_default_app(worker_app) # for the rest of the process
497
+
498
+ with set_default_app(test_app): # only inside the block
499
+ await job()
500
+ ```
501
+
502
+ A `resolve()` failing inside a route answers with a 422, or closes a websocket: `add_injection` registers `dependency_resolution_handler` unless a handler for `DependencyResolutionError` exists or `handle_resolution_errors=False` is passed.
503
+
504
+ The default lives in a context variable, so it reaches the tasks started after it is set: set it at startup, not inside a task that other tasks will not see.
505
+
395
506
  Anything called from the handler — including `@inject`-ed helpers — resolves against the request's cache, so a per-request dependency like a DB session stays a single instance for the whole request. The context is opened by a middleware, so `resolve` also works inside middleware added before it (before routing, `request.scope["route"]` and path params are not available yet).
396
507
 
397
508
  WebSocket routes work the same way: the context is bound to the `WebSocket` instead of a `Request`, and dependencies that ask for one get it. A websocket handed to a dependency shares its handshake with the one the route received, so it can be talked through after the route has called `accept()`:
@@ -449,20 +560,21 @@ The root package is what you need to use the library, and the surface a release
449
560
  | | |
450
561
  | --- | --- |
451
562
  | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
452
- | Resolving | `inject`, `resolve`, `bind_deps` |
453
- | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
563
+ | Resolving | `inject`, `resolve`, `bind_deps`, `NotNone` |
564
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `ContextValue`, `synthetic_request`, `set_default_app`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
454
565
  | FastAPI integration | `add_injection` |
455
- | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
566
+ | Errors | `DependencyResolutionError`, `NoInjectionContextError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
456
567
 
457
568
  Code that builds on the library imports from the submodule that owns the piece. These are public too:
458
569
 
459
570
  | Module | Names |
460
571
  | --- | --- |
461
- | `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `strip_annotation`, `as_depends`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `UnboundDepArgsError` |
572
+ | `fastapi_injected.ext` | `MakeDataclass`, `MakeInjected`, `signature_with_deps`, `remap_dep_args`, `is_dep`, `is_arg`, `is_request_param`, `unwrap_dep_tp`, `unwrap_dep_dependency`, `unwrap_tp`, `strip_annotation`, `annotated`, `as_depends`, `DependsSource`, `clear_dependant_cache`, `ensure_injection_ctx`, `MissedDependencyError`, `NotAsyncError`, `UnboundDepArgsError` |
462
573
  | `fastapi_injected.types` | `DepOf`, `ArgMarker`, `HasDependsHook`, and the typing vocabulary the signatures are written in — `DepReturn`, `DepShape`, `DepDecl`, `AsyncFunc`, `Coro`, `BoundConnection`, `DependencyCache` and friends |
463
- | `fastapi_injected.overrides` | `Overrides`, `OverridesProvider` |
574
+ | `fastapi_injected.overrides` | `Overrides`, `OverridesProvider`, `OverrideBlock` |
464
575
  | `fastapi_injected.signature` | `Signature`, `ParamRole` |
465
- | `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `MissingDependencyCacheError` |
576
+ | `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `dependency_resolution_handler`, `install_dependency_cache`, `MissingDependencyCacheError` |
577
+ | `fastapi_injected.openapi` | `add_openapi_hook`, `add_openapi`, `invalidate_openapi`, `HasDocDepends`, `iter_doc_depends`, `OpenAPIHook` |
466
578
  | `fastapi_injected.reflect` | `iter_dependant`, `iter_calls`, `iter_security`, `iter_params`, `find_dependant`, `iter_overridden`, `iter_routes`, `iter_api_routes`, `iter_routes_where`, `find_route`, `match_route`, `iter_routers`, `response_type`, `add_route_dependency`, `add_lifespan`, `iter_operations`, `operation_for`, `as_dependant` |
467
579
 
468
580
  Anything else, including every module whose name starts with an underscore, is machinery that can change in a patch release.
@@ -1,6 +1,15 @@
1
1
  from ._bind import bind_deps
2
2
  from ._given import Given
3
- from .ctx import InjectionContext, UnboundContextError, injection_ctx, synthetic_request
3
+ from ._not_none import NotNone
4
+ from .ctx import (
5
+ ContextValue,
6
+ InjectionContext,
7
+ NoInjectionContextError,
8
+ UnboundContextError,
9
+ injection_ctx,
10
+ set_default_app,
11
+ synthetic_request,
12
+ )
4
13
  from .deps import DependencyResolutionError, UnnamedParamError
5
14
  from .fastapi import add_injection
6
15
  from .inject import inject
@@ -11,6 +20,7 @@ from .types import Arg, Dep, DepFactory, Injected
11
20
 
12
21
  __all__ = [
13
22
  "Arg",
23
+ "ContextValue",
14
24
  "Dep",
15
25
  "DepFactory",
16
26
  "DependencyResolutionError",
@@ -18,7 +28,9 @@ __all__ = [
18
28
  "Given",
19
29
  "Injected",
20
30
  "InjectionContext",
31
+ "NoInjectionContextError",
21
32
  "NotADependencyError",
33
+ "NotNone",
22
34
  "UnboundContextError",
23
35
  "UnnamedParamError",
24
36
  "ValueOverride",
@@ -29,5 +41,6 @@ __all__ = [
29
41
  "override_app",
30
42
  "push_overrides",
31
43
  "resolve",
44
+ "set_default_app",
32
45
  "synthetic_request",
33
46
  ]
@@ -7,6 +7,7 @@ from fastapi.params import Depends
7
7
 
8
8
  from ._calls import annotated
9
9
  from ._deps_tp import unwrap_tp
10
+ from .deps import _named_param
10
11
  from .signature import Signature
11
12
  from .types import AsyncFunc, DepOf, Func
12
13
 
@@ -41,7 +42,12 @@ def _dep_annotation(dep: DepOf[Any] | Callable[..., Any], /) -> Any:
41
42
  if isinstance(dep, Depends):
42
43
  return annotated(Any, dep)
43
44
 
44
- if _is_annotation(dep) or not callable(dep):
45
+ if _is_annotation(dep):
46
+ # bound, a marker is read under the made-up `__dep_arg_N` name, so it must name its own
47
+ _named_param(unwrap_tp(dep))
48
+ return dep
49
+
50
+ if not callable(dep):
45
51
  return dep
46
52
 
47
53
  return annotated(Any, Depends(dep))
@@ -82,7 +88,23 @@ def take_dep_args(kwargs: dict[str, Any], /) -> list[Any]:
82
88
  return [kwargs.pop(dep_arg_name(index)) for index in indexes]
83
89
 
84
90
 
91
+ class NotAsyncError(TypeError):
92
+ def __init__(self, func: Callable[..., Any], /) -> None:
93
+ super().__init__(f"{func!r} must be an async function")
94
+
95
+ self.func = func
96
+
97
+
98
+ def _is_async_callable(func: Any, /) -> bool:
99
+ return inspect.iscoroutinefunction(inspect.unwrap(func)) or (
100
+ not inspect.isclass(func) and inspect.iscoroutinefunction(getattr(func, "__call__", None)) # noqa: B004
101
+ )
102
+
103
+
85
104
  def remap_dep_args[**P, R](func: AsyncFunc[P, R], /) -> AsyncFunc[P, R]:
105
+ if not _is_async_callable(func):
106
+ raise NotAsyncError(func)
107
+
86
108
  @wraps(func)
87
109
  async def wrapper(*args: Any, **kwargs: Any) -> R:
88
110
  return await func(*args, *take_dep_args(kwargs), **kwargs)
@@ -167,6 +189,7 @@ def bind_deps[**P, R](
167
189
 
168
190
 
169
191
  __all__ = [
192
+ "NotAsyncError",
170
193
  "UnboundDepArgsError",
171
194
  "bind_deps",
172
195
  "dep_arg_name",
@@ -1,3 +1,4 @@
1
+ import sys
1
2
  import types
2
3
  import typing
3
4
  from collections.abc import Callable
@@ -10,10 +11,23 @@ from typing_inspection.typing_objects import is_typealiastype
10
11
  from .types import ArgMarker, HasDependsHook
11
12
 
12
13
 
14
+ def _alias_value(alias: Any, /) -> Any:
15
+ try:
16
+ return alias.__value__
17
+ except NameError:
18
+ # a `TYPE_CHECKING`-only name: leave it a forward reference
19
+ if sys.version_info < (3, 14):
20
+ raise
21
+
22
+ from annotationlib import Format, call_evaluate_function # noqa: PLC0415
23
+
24
+ return call_evaluate_function(alias.evaluate_value, Format.FORWARDREF)
25
+
26
+
13
27
  def unwrap_tp(tp: Any) -> Any:
14
28
  # PEP 695 aliases can be nested, e.g. `type A = B` where `type B = Annotated[...]`
15
29
  while is_typealiastype(tp):
16
- tp = tp.__value__
30
+ tp = _alias_value(tp)
17
31
 
18
32
  return tp
19
33