|
4 | 4 |
|
5 | 5 | ## [FastAPI](https://github.com/fastapi/fastapi) |
6 | 6 |
|
7 | | -Exemple: |
| 7 | +### Inject a dependency |
| 8 | + |
| 9 | +Here's how to inject an instance into a FastAPI endpoint. |
| 10 | + |
| 11 | +> Import: |
8 | 12 |
|
9 | 13 | ```python |
10 | | -from fastapi import FastAPI |
11 | 14 | from injection.integrations.fastapi import Inject |
| 15 | +``` |
12 | 16 |
|
13 | | -app = FastAPI() |
| 17 | +> With **Annotated**: |
14 | 18 |
|
| 19 | +```python |
15 | 20 | @app.get("/") |
16 | | -async def my_endpoint(service: MyService = Inject(MyService)): |
| 21 | +async def my_endpoint( |
| 22 | + service: Annotated[MyService, Inject(MyService)], |
| 23 | +) -> None: |
17 | 24 | ... |
18 | 25 | ``` |
| 26 | + |
| 27 | +> Without **Annotated**: |
| 28 | +
|
| 29 | +```python |
| 30 | +@app.get("/") |
| 31 | +async def my_endpoint( |
| 32 | + service: MyService = Inject(MyService), |
| 33 | +) -> None: |
| 34 | + ... |
| 35 | +``` |
| 36 | + |
| 37 | +### Useful scopes |
| 38 | + |
| 39 | +Two fairly common scopes in FastAPI: |
| 40 | +* **Application lifespan scope**: associate with application lifespan. |
| 41 | +* **Request scope**: associate with http request lifetime. |
| 42 | + |
| 43 | +_For a better understanding of the scopes, [here's the associated documentation](scoped-dependencies.md)._ |
| 44 | + |
| 45 | +Here's how to configure FastAPI: |
| 46 | + |
| 47 | +```python |
| 48 | +from collections.abc import AsyncIterator, Awaitable, Callable |
| 49 | +from contextlib import asynccontextmanager |
| 50 | +from enum import StrEnum, auto |
| 51 | + |
| 52 | +from fastapi import FastAPI, Request, Response |
| 53 | +from injection import adefine_scope |
| 54 | + |
| 55 | +class InjectionScope(StrEnum): |
| 56 | + LIFESPAN = auto() |
| 57 | + REQUEST = auto() |
| 58 | + |
| 59 | +@asynccontextmanager |
| 60 | +async def lifespan(_: FastAPI) -> AsyncIterator[None]: |
| 61 | + async with adefine_scope(InjectionScope.LIFESPAN, shared=True): |
| 62 | + yield |
| 63 | + |
| 64 | +app = FastAPI(lifespan=lifespan) |
| 65 | + |
| 66 | +@app.middleware("http") |
| 67 | +async def define_request_scope_middleware( |
| 68 | + request: Request, |
| 69 | + handler: Callable[[Request], Awaitable[Response]], |
| 70 | +) -> Response: |
| 71 | + async with adefine_scope(InjectionScope.REQUEST): |
| 72 | + return await handler(request) |
| 73 | +``` |
0 commit comments