fastapi-injected 0.3.5__tar.gz → 0.4.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 (83) hide show
  1. fastapi_injected-0.4.0/PKG-INFO +493 -0
  2. fastapi_injected-0.4.0/README.md +472 -0
  3. fastapi_injected-0.4.0/fastapi_injected/__init__.py +33 -0
  4. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_bind.py +16 -23
  5. fastapi_injected-0.4.0/fastapi_injected/_body.py +108 -0
  6. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_cache.py +3 -3
  7. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_calls.py +36 -20
  8. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_deps_tp.py +45 -2
  9. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_overrides.py +3 -0
  10. fastapi_injected-0.3.5/fastapi_injected/scope.py → fastapi_injected-0.4.0/fastapi_injected/ctx.py +150 -63
  11. fastapi_injected-0.4.0/fastapi_injected/deps.py +185 -0
  12. fastapi_injected-0.4.0/fastapi_injected/ext.py +23 -0
  13. fastapi_injected-0.3.5/fastapi_injected/_fastapi_lifecycle.py → fastapi_injected-0.4.0/fastapi_injected/fastapi.py +44 -14
  14. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/inject.py +13 -12
  15. fastapi_injected-0.4.0/fastapi_injected/overrides.py +54 -0
  16. fastapi_injected-0.4.0/fastapi_injected/reflect/__init__.py +53 -0
  17. fastapi_injected-0.4.0/fastapi_injected/reflect/_dependant.py +193 -0
  18. fastapi_injected-0.4.0/fastapi_injected/reflect/_openapi.py +48 -0
  19. fastapi_injected-0.4.0/fastapi_injected/reflect/_routes.py +271 -0
  20. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/resolve.py +14 -15
  21. fastapi_injected-0.4.0/fastapi_injected/signature.py +219 -0
  22. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/types.py +12 -1
  23. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/pyproject.toml +3 -2
  24. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/annotations.py +2 -1
  25. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/bind.py +4 -3
  26. fastapi_injected-0.4.0/tests/_typing/ctx.py +67 -0
  27. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/dataclass.py +1 -1
  28. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/inject.py +7 -7
  29. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/injected.py +2 -1
  30. fastapi_injected-0.4.0/tests/_typing/integration.py +41 -0
  31. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/overrides.py +6 -6
  32. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/resolve.py +2 -2
  33. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_bind.py +6 -13
  34. fastapi_injected-0.4.0/tests/test_body.py +524 -0
  35. fastapi_injected-0.4.0/tests/test_body_reads.py +266 -0
  36. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_cache.py +14 -14
  37. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_calls.py +23 -12
  38. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_concurrency.py +8 -8
  39. fastapi_injected-0.3.5/tests/test_scope.py → fastapi_injected-0.4.0/tests/test_ctx.py +12 -12
  40. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_dataclass.py +2 -1
  41. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_dependant_cache.py +9 -10
  42. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_fastapi.py +76 -63
  43. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_given.py +4 -3
  44. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_inject.py +7 -7
  45. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_injected.py +3 -2
  46. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_overrides.py +14 -6
  47. fastapi_injected-0.4.0/tests/test_reflect.py +484 -0
  48. fastapi_injected-0.4.0/tests/test_request_params.py +175 -0
  49. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_resolve.py +4 -4
  50. fastapi_injected-0.4.0/uv.lock +819 -0
  51. fastapi_injected-0.3.5/PKG-INFO +0 -386
  52. fastapi_injected-0.3.5/README.md +0 -365
  53. fastapi_injected-0.3.5/fastapi_injected/__init__.py +0 -57
  54. fastapi_injected-0.3.5/fastapi_injected/deps.py +0 -183
  55. fastapi_injected-0.3.5/fastapi_injected/overrides.py +0 -36
  56. fastapi_injected-0.3.5/fastapi_injected/sign.py +0 -78
  57. fastapi_injected-0.3.5/tests/_typing/integration.py +0 -38
  58. fastapi_injected-0.3.5/tests/_typing/scope.py +0 -67
  59. fastapi_injected-0.3.5/uv.lock +0 -775
  60. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.github/dependabot.yml +0 -0
  61. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.github/workflows/automerge.yml +0 -0
  62. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.github/workflows/lint.yml +0 -0
  63. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.github/workflows/publish.yml +0 -0
  64. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.github/workflows/test.yml +0 -0
  65. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.gitignore +0 -0
  66. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/.pre-commit-config.yaml +0 -0
  67. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/LICENSE +0 -0
  68. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_dataclass.py +0 -0
  69. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_given.py +0 -0
  70. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_injected.py +0 -0
  71. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/fastapi_injected/_rlock.py +0 -0
  72. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/__init__.py +0 -0
  73. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/__init__.py +0 -0
  74. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/arg.py +0 -0
  75. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/deps.py +0 -0
  76. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/errors.py +0 -0
  77. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/given.py +0 -0
  78. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/_typing/markers.py +0 -0
  79. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/deps.py +0 -0
  80. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/ext/__init__.py +0 -0
  81. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/ext/test_pydantic_ai.py +0 -0
  82. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_errors.py +0 -0
  83. {fastapi_injected-0.3.5 → fastapi_injected-0.4.0}/tests/test_rlock.py +0 -0
@@ -0,0 +1,493 @@
1
+ Metadata-Version: 2.5
2
+ Name: fastapi-injected
3
+ Version: 0.4.0
4
+ Summary: Yet another library to reuse fastapi dependency injection
5
+ Project-URL: Repository, https://github.com/uriyyo/fastapi-injected
6
+ Author-email: Yurii Karabas <1998uriyyo@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: fastapi>=0.141.0
18
+ Requires-Dist: typing-extensions>=4.16.0
19
+ Requires-Dist: typing-inspection>=0.4.4
20
+ Description-Content-Type: text/markdown
21
+
22
+ # fastapi-injected
23
+
24
+ Yet another attempt to reuse FastAPI's dependency injection outside of request handlers.
25
+
26
+ This is an opinionated library: it takes the DI machinery you already know from FastAPI (`Depends`, generator dependencies with teardown, dependency caching) and makes it usable in plain async functions — background jobs, CLI commands, workers, scripts — without a `Request` in sight.
27
+
28
+ ## Installation
29
+
30
+ ```sh
31
+ pip install fastapi-injected
32
+ ```
33
+
34
+ Requires Python 3.12+.
35
+
36
+ ## Usage
37
+
38
+ Declare dependencies as regular classes and annotate fields with `Dep[...]`:
39
+
40
+ ```python
41
+ from dataclasses import dataclass
42
+ from typing import AsyncIterator
43
+
44
+ from fastapi_injected import Dep, DepFactory, Injected, inject
45
+
46
+
47
+ @dataclass
48
+ class Session:
49
+ closed: bool = False
50
+
51
+
52
+ async def session_dep() -> AsyncIterator[Session]:
53
+ session = Session()
54
+ try:
55
+ yield session
56
+ finally:
57
+ session.closed = True
58
+
59
+
60
+ @dataclass
61
+ class Repository:
62
+ session: DepFactory[Session, session_dep]
63
+
64
+
65
+ @dataclass
66
+ class Service:
67
+ repo: Dep[Repository]
68
+
69
+
70
+ @inject
71
+ async def handler(*, service: Dep[Service] = Injected) -> None:
72
+ ... # service is built and injected, session is closed on exit
73
+
74
+
75
+ await handler()
76
+ ```
77
+
78
+ - `Dep[T]` — resolve `T` by calling it, same as FastAPI's `Annotated[T, Depends()]`.
79
+ - `DepFactory[T, factory]` — resolve `T` via a factory, same as `Annotated[T, Depends(factory)]`. Generator factories get proper teardown.
80
+ - `Arg[T]` — keep a parameter out of the dependency graph even though its annotation is a dependency, so the caller supplies it. See [Caller-supplied arguments](#caller-supplied-arguments).
81
+ - `Injected` — a sentinel default that exists purely to make type checkers happy: without it they would complain about a missing argument at call sites. At runtime the parameter is always filled in by `@inject`.
82
+
83
+ Injected parameters mix freely with regular ones — pass your own arguments as usual and the rest is injected:
84
+
85
+ ```python
86
+ @inject
87
+ async def add(a: int, b: int, *, service: Dep[Service] = Injected) -> int:
88
+ ...
89
+
90
+
91
+ result = await add(1, 2)
92
+ ```
93
+
94
+ ### Caller-supplied arguments
95
+
96
+ A parameter is injected only if it is written as a dependency — `Dep[...]`, `DepFactory[...]`, an `Annotated[..., Depends(...)]` of your own, or a `Depends(...)` default. Everything else is left for the caller, annotation untouched: it is never handed to pydantic, so any type works with no marker at all.
97
+
98
+ ```python
99
+ class Connection: # not a pydantic-friendly type, and it does not have to be
100
+ ...
101
+
102
+
103
+ @inject
104
+ async def handler(conn: Connection, *, service: Dep[Service] = Injected) -> None:
105
+ ...
106
+
107
+
108
+ await handler(connection)
109
+ ```
110
+
111
+ `Arg[...]` is for the opposite case — a parameter that *is* spelled as a dependency, in a function that wants it passed in instead:
112
+
113
+ ```python
114
+ from fastapi_injected import Arg
115
+
116
+ type ServiceDep = Annotated[Service, Depends(get_service)]
117
+
118
+
119
+ @inject
120
+ async def handler(service: Arg[ServiceDep], *, session: Dep[Session] = Injected) -> None:
121
+ ...
122
+
123
+
124
+ await handler(service)
125
+ ```
126
+
127
+ `Arg[T]` is a no-op for type checkers — the parameter stays typed as `T` — and at runtime it tells `@inject` to keep this parameter out of the dependency graph.
128
+
129
+ Writing `Injected` as the default of a parameter that is not a dependency raises `NotADependencyError` at decoration time, since nothing would ever fill it in.
130
+
131
+ ### Resolving a type directly
132
+
133
+ No decorator needed — resolve a dependency graph on demand:
134
+
135
+ ```python
136
+ from fastapi_injected import resolve
137
+
138
+ service = await resolve(Service)
139
+ ```
140
+
141
+ Like `@inject`, `resolve` accepts `new_ctx=True` to force a fresh context instead of reusing the surrounding one.
142
+
143
+ ### Contexts and caching
144
+
145
+ By default every call to an injected function gets its own injection context: dependencies are built, cached within the call, and torn down when it returns. Wrap several calls in `injection_ctx()` to share one cache (and defer teardown to the end of the context):
146
+
147
+ ```python
148
+ from fastapi_injected import injection_ctx
149
+
150
+ async with injection_ctx():
151
+ a = await handler() # dependencies built here
152
+ b = await handler() # same instances reused
153
+ # generator dependencies are torn down here
154
+ ```
155
+
156
+ Use `@inject(new_ctx=True)` to opt a function out of the surrounding context and always get fresh dependencies. It builds them again, but stays in the request they are being built for, so request-bound dependencies keep resolving.
157
+
158
+ Outside of a request there is no request to resolve against, so the context makes one up. It answers what a dependency usually reads — `method`, `url`, `headers`, `path_params`, `client`, `state` — with the values of a request nobody sent. The application is the one thing it cannot invent: pass it when a dependency reaches for `request.app`:
159
+
160
+ ```python
161
+ async with injection_ctx(app=app):
162
+ await handler() # `request.app.state` resolves as it does in a route
163
+ ```
164
+
165
+ Without it, reading `request.app` raises a `KeyError` naming what is missing rather than a bare `'app'`.
166
+
167
+ 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:
168
+
169
+ ```python
170
+ from fastapi_injected import injection_ctx, synthetic_request
171
+
172
+ request = synthetic_request(
173
+ headers={"x-trace": "job-42"},
174
+ cookies={"sid": "abc"},
175
+ query_params={"page": "2"},
176
+ path_params={"item_id": 7},
177
+ body={"name": "readme"}, # sent as JSON; bytes and str are sent as they are
178
+ app=app,
179
+ )
180
+
181
+ async with injection_ctx(request=request):
182
+ await handler() # `Header()`, `Cookie()`, `Query()`, `Path()` and `Body()` resolve from it
183
+ ```
184
+
185
+ 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.
186
+
187
+ ### Overriding dependencies
188
+
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:
190
+
191
+ ```python
192
+ from fastapi_injected import push_overrides
193
+
194
+ with push_overrides({Session: Session(closed=True)}):
195
+ await handler() # gets the override instead of the real dependency
196
+ ```
197
+
198
+ A key can be the dependency itself, or the annotation you wrote in the signature — `Dep[Session]` and `DepFactory[Session, session_dep]` both work and are normalized to the same underlying dependency:
199
+
200
+ ```python
201
+ with push_overrides({DepFactory[Session, session_dep]: my_session}):
202
+ ...
203
+ ```
204
+
205
+ A callable value is called to produce the dependency, as in FastAPI's `dependency_overrides`; anything else is injected as it is. Two wrappers make the intent explicit and cover the ambiguous cases:
206
+
207
+ - `ValueOverride(value)` — always inject `value`, even when it is itself callable (a class, a mock, a function object).
208
+ - `FactoryOverride(factory)` — call `factory` to produce the value. Sync, async, and generator factories are all supported, with the same teardown semantics as regular dependencies.
209
+
210
+ ```python
211
+ from fastapi_injected import FactoryOverride, ValueOverride
212
+
213
+ with push_overrides(
214
+ {
215
+ Session: ValueOverride(fake_session),
216
+ Repository: FactoryOverride(lambda: FakeRepository()),
217
+ },
218
+ ):
219
+ ...
220
+ ```
221
+
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.
223
+
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
+ ```python
227
+ async with injection_ctx():
228
+ real = await handler() # dependencies cached here
229
+
230
+ with push_overrides({Session: fake}):
231
+ await handler() # rebuilt with `fake`, everything else reused from the cache
232
+
233
+ await handler() # back to the cached, real dependencies
234
+ ```
235
+
236
+ Overrides can also be handed to the context directly, which is the same thing in one call:
237
+
238
+ ```python
239
+ async with injection_ctx({Session: fake}) as ctx:
240
+ await handler()
241
+
242
+ with ctx.override({Session: other}): # nest freely
243
+ await handler()
244
+ ```
245
+
246
+ 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.
247
+
248
+ ### Dependencies that are objects
249
+
250
+ 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.
251
+
252
+ `MakeDataclass` is a base class that makes its subclasses dataclasses with a hash that always answers: by fields when they can be hashed, by identity when they cannot.
253
+
254
+ ```python
255
+ from dataclasses import field
256
+ from fastapi_injected import resolve
257
+ from fastapi_injected.ext import MakeDataclass
258
+
259
+
260
+ class Settings(MakeDataclass):
261
+ hosts: list[str] = field(default_factory=list)
262
+
263
+ def __call__(self) -> list[str]:
264
+ return self.hosts
265
+
266
+
267
+ await resolve(Settings(["a", "b"])) # a plain dataclass would raise TypeError here
268
+ ```
269
+
270
+ Every `dataclasses.dataclass` option is accepted as a class keyword and passed straight through:
271
+
272
+ ```python
273
+ class Config(MakeDataclass, frozen=True, kw_only=True):
274
+ retries: int = 3
275
+ ```
276
+
277
+ ### When resolution fails
278
+
279
+ A dependency can fail to resolve for the same reasons it would in a route — a missing header, a query parameter that does not validate. `DependencyResolutionError` carries those errors in the shape pydantic produced them, and turns into the response FastAPI would have returned:
280
+
281
+ ```python
282
+ from fastapi_injected import DependencyResolutionError
283
+
284
+ try:
285
+ await handler()
286
+ except DependencyResolutionError as exc:
287
+ exc.errors # [{'type': 'missing', 'loc': ('header', 'x-trace'), ...}]
288
+ raise exc.as_validation_error() from exc # a RequestValidationError, so a 422
289
+ ```
290
+
291
+ It is a `ValueError`, which is what resolution used to raise, so code catching that keeps working.
292
+
293
+ ### Dependencies decided at runtime
294
+
295
+ 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:
296
+
297
+ ```python
298
+ from fastapi_injected import Given, resolve
299
+
300
+ doc = Doc(title="readme")
301
+
302
+ await resolve(Given(doc)) # the doc itself
303
+ ```
304
+
305
+ Constants holding equal values are the same dependency, so they share a cache entry and can be overridden like any other. What `Given` returns is a marker held as a value — `DepOf[R]`, as opposed to `Dep[R]`, which is the same marker in annotation position.
306
+
307
+ `bind_deps` binds such markers to the leading parameters of a function, which is how a dependency graph gets built from markers that were not known when the function was written:
308
+
309
+ ```python
310
+ from fastapi_injected import bind_deps
311
+
312
+ async def describe(doc: Doc, role: Role) -> str:
313
+ return f"{doc.title}:{role.name}"
314
+
315
+
316
+ bound = bind_deps(describe, Given(doc), RoleDep)
317
+
318
+ await resolve(bound) # "readme:admin", with `role` resolved as usual
319
+ ```
320
+
321
+ What a parameter is bound to can be written any way a dependency can be: a marker like `Given(...)`, `Dep[T]` or `DepFactory[T, factory]`, a `Depends(...)`, or the callable itself — the same things `resolve` accepts.
322
+
323
+ 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.
324
+
325
+ ### Dependencies as objects
326
+
327
+ 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.
328
+
329
+ ```python
330
+ from fastapi_injected import Given
331
+ from fastapi_injected.ext import MakeInjected
332
+ from fastapi_injected.types import DepOf
333
+
334
+
335
+ class IsOwner(MakeInjected):
336
+ doc: DepOf[Doc]
337
+ role: DepOf[Role]
338
+ loud: bool = False # a plain field stays a plain field
339
+
340
+ async def __call__(self, doc: Doc, role: Role) -> bool:
341
+ return doc.owner == role.name
342
+
343
+
344
+ await resolve(IsOwner(doc=Given(doc), role=RoleDep))
345
+ ```
346
+
347
+ 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.
348
+
349
+ ### Inspecting annotations
350
+
351
+ `fastapi_injected.ext` holds a few helpers for code that needs to reason about `Dep[...]` annotations — building override maps, custom decorators, and the like:
352
+
353
+ - `is_dep(tp)` — whether `tp` is a `Dep`/`DepFactory` annotation.
354
+ - `unwrap_dep_tp(tp)` — the annotated type (`Any` for a bare `Dep`).
355
+ - `unwrap_dep_dependency(tp)` — the callable that resolves it: the factory for `DepFactory[T, factory]`, the type itself for `Dep[T]`.
356
+
357
+ ### Reflecting on apps and dependency trees
358
+
359
+ `fastapi_injected.reflect` answers the questions tests and tooling keep asking about an app, without walking `Dependant` trees or `app.routes` by hand.
360
+
361
+ ```python
362
+ from fastapi_injected.reflect import find_route, iter_api_routes, iter_calls, iter_security
363
+
364
+ # every APIRoute with its full path, through include_router, Mount and Host
365
+ for path, route in iter_api_routes(app):
366
+ assert get_current_user in iter_calls(route.dependant), path
367
+
368
+ route = find_route(app, method="POST", path="/items") # or name="create_item"
369
+
370
+ # security schemes a route (or any callable) pulls in, with their OAuth scopes
371
+ assert list(iter_security(route.dependant)) == [(bearer, ["items:write"])]
372
+ ```
373
+
374
+ - `iter_dependant(root, *, mode="bfs" | "dfs")` — every `Dependant` under `root`, the root first.
375
+ - `iter_calls(root, *, expand=None)` — unique callables `root` depends on, the root itself excluded. `expand(call)` returns extra calls to report for callables that hold more dependencies than their signature shows, such as composite permissions.
376
+ - `iter_security(root)` — `(scheme, scopes)` for every `SecurityBase` in the tree.
377
+ - `find_dependant(root, call)` — the chain of dependants from the root down to `call`, for saying *through what* a dependency is reached.
378
+ - `iter_overridden(root, overrides)` — the calls an override map or collection replaces, including every dependant above a replaced one, which is what stops caching across an override.
379
+ - `iter_routes(app)` — `(path, route)` for every route, with mounts, hosts and included routers expanded and the path prefixed accordingly. `iter_api_routes` keeps only FastAPI's HTTP and websocket routes, and `find_route(app, *, method=, path=, name=)` returns the first one matching every given filter, raising `LookupError` otherwise. Websocket routes answer to the method `WEBSOCKET`.
380
+ - `iter_routes_where(app, pred)` — `(method, path, route)` for every route `pred` accepts, one entry per method. The usual authorization test is `iter_routes_where(app, lambda r: guard not in iter_calls(r.dependant))`.
381
+ - `iter_operations(app_or_schema)` and `operation_for(app_or_schema, method, path)` — walk the OpenAPI document by `(path, method, operation)` instead of indexing nested dicts.
382
+ - `iter_routers(app)` — `(prefix, router)` for the app's router and every router included or mounted under it.
383
+ - `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.
384
+ - `iter_params(root)` — `(dependant, kind, field)` for every path, query, header, cookie and body parameter in the tree.
385
+ - `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`.
386
+ - `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.
387
+ - `.add(*parameters)` — extra keyword-only parameters before `**kwargs`; names already present are kept as they are.
388
+ - `.drop(*names)` and `.update(name, **changes)` — drop parameters a wrapper consumes itself, or change one parameter's annotation, default or kind.
389
+ - `.add_dep(name, dep, *, annotation=Any)` — a parameter FastAPI resolves with a `Depends`/`Security` marker or a callable.
390
+ - `.prepend(*parameters)`, `.rename(old, new)` and `.returns(annotation)` — positional parameters at the front, a renamed parameter, a new return annotation.
391
+ - `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.
392
+ - `.wrap(func)` — a forwarder to `func`, async when `func` is, carrying this signature; `.apply(func)` sets the signature on `func` itself.
393
+ - `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.
394
+ - `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.
395
+
396
+ `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.
397
+
398
+ ### FastAPI request integration
399
+
400
+ 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:
401
+
402
+ ```python
403
+ from fastapi import FastAPI
404
+ from fastapi_injected import Dep, add_injection, resolve
405
+
406
+ app = FastAPI()
407
+ add_injection(app)
408
+
409
+
410
+ @app.get("/")
411
+ async def route(service: Dep[Service]) -> str:
412
+ same = await resolve(Service) # same instance as `service`
413
+ ...
414
+ ```
415
+
416
+ 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).
417
+
418
+ 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()`:
419
+
420
+ ```python
421
+ async def notify(websocket: WebSocket) -> None:
422
+ await websocket.send_json({"ready": True})
423
+
424
+
425
+ @app.websocket("/ws")
426
+ async def ws_route(websocket: WebSocket, service: Dep[Service]) -> None:
427
+ await websocket.accept()
428
+ await resolve(notify) # sends through the connection the route accepted
429
+ ```
430
+
431
+ Dependencies that take request parameters — `Header()`, `Cookie()`, `Query()`, `Path()`, and the body as `Body()`, `Form()`, `File()` or a pydantic model — resolve from the request the context is bound to, exactly as they would in the route:
432
+
433
+ ```python
434
+ class Item(BaseModel):
435
+ name: str
436
+
437
+
438
+ async def get_item(item: Item) -> Item:
439
+ return item
440
+
441
+
442
+ @app.post("/items")
443
+ async def create(request: Request) -> str:
444
+ item = await resolve(get_item) # the request body, parsed as FastAPI would
445
+ ...
446
+ ```
447
+
448
+ A request parameter is a dependency of its own as well - resolve a marker, or an annotation carrying one, without writing a function around it. On its own it has no parameter name, so the marker says what to read; a marker without an alias raises `UnnamedParamError`:
449
+
450
+ ```python
451
+ api_key = await resolve(Header(alias="x-api-key")) # the raw header, as `Any`
452
+ page = await resolve(Annotated[int, Query(alias="page")]) # validated as `int`
453
+ item_id = await resolve(Annotated[int, Path(alias="item_id")])
454
+ item = await resolve(Annotated[Item, Body()]) # the whole body needs no name
455
+
456
+
457
+ @inject
458
+ async def handler(*, api_key: Annotated[str, Header()] = Injected) -> str:
459
+ return api_key # a parameter has a name - `x-api-key`, as FastAPI derives it
460
+ ```
461
+
462
+ The body is read only when the resolved dependency declares one, and it is read once per request, shared with the route and every context nested in it. When the route itself declares a body, dependencies see it in the shape the route gave it: a route with several body parameters embeds them under their names, and a dependency reads its own from there.
463
+
464
+ `injection_ctx(request=...)` accepts either a `Request` or a `WebSocket`, and so does everything that reads `InjectionContext.request` — the union is `fastapi_injected.types.BoundConnection`.
465
+
466
+ ## What is public
467
+
468
+ The root package is what you need to use the library, and the surface a release keeps:
469
+
470
+ | | |
471
+ | --- | --- |
472
+ | Markers | `Dep`, `DepFactory`, `Arg`, `Given`, `Injected` |
473
+ | Resolving | `inject`, `resolve`, `bind_deps` |
474
+ | Contexts and overrides | `InjectionContext`, `injection_ctx`, `synthetic_request`, `push_overrides`, `override_app`, `ValueOverride`, `FactoryOverride` |
475
+ | FastAPI integration | `add_injection` |
476
+ | Errors | `DependencyResolutionError`, `NotADependencyError`, `UnboundContextError`, `UnnamedParamError` |
477
+
478
+ Code that builds on the library imports from the submodule that owns the piece. These are public too:
479
+
480
+ | Module | Names |
481
+ | --- | --- |
482
+ | `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` |
483
+ | `fastapi_injected.types` | `DepOf`, `ArgMarker`, `HasDependsHook`, and the typing vocabulary the signatures are written in — `DepReturn`, `DepShape`, `DepDecl`, `AsyncFunc`, `Coro`, `BoundConnection`, `DependencyCache` and friends |
484
+ | `fastapi_injected.overrides` | `Overrides`, `OverridesProvider` |
485
+ | `fastapi_injected.signature` | `Signature`, `ParamRole` |
486
+ | `fastapi_injected.fastapi` | `InjectionMiddleware`, `bind_injection_ctx`, `MissingDependencyCacheError` |
487
+ | `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` |
488
+
489
+ Anything else, including every module whose name starts with an underscore, is machinery that can change in a patch release.
490
+
491
+ ## License
492
+
493
+ MIT