notslowapi 0.1.0__py3-none-any.whl

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 (102) hide show
  1. notslowapi/.agents/skills/fastapi/SKILL.md +321 -0
  2. notslowapi/.agents/skills/fastapi/references/dependencies.md +142 -0
  3. notslowapi/.agents/skills/fastapi/references/other-tools.md +76 -0
  4. notslowapi/.agents/skills/fastapi/references/path-operations.md +93 -0
  5. notslowapi/.agents/skills/fastapi/references/pydantic.md +93 -0
  6. notslowapi/.agents/skills/fastapi/references/responses.md +79 -0
  7. notslowapi/.agents/skills/fastapi/references/streaming.md +105 -0
  8. notslowapi/__init__.py +27 -0
  9. notslowapi/__main__.py +3 -0
  10. notslowapi/_compat/__init__.py +40 -0
  11. notslowapi/_compat/shared.py +222 -0
  12. notslowapi/_compat/v2.py +504 -0
  13. notslowapi/applications.py +4778 -0
  14. notslowapi/background.py +61 -0
  15. notslowapi/cli.py +13 -0
  16. notslowapi/concurrency.py +45 -0
  17. notslowapi/datastructures.py +186 -0
  18. notslowapi/dependencies/__init__.py +0 -0
  19. notslowapi/dependencies/models.py +234 -0
  20. notslowapi/dependencies/utils.py +1057 -0
  21. notslowapi/encoders.py +394 -0
  22. notslowapi/exception_handlers.py +37 -0
  23. notslowapi/exceptions.py +258 -0
  24. notslowapi/logger.py +3 -0
  25. notslowapi/middleware/__init__.py +1 -0
  26. notslowapi/middleware/asyncexitstack.py +18 -0
  27. notslowapi/middleware/cors.py +1 -0
  28. notslowapi/middleware/exceptions.py +5 -0
  29. notslowapi/middleware/gzip.py +1 -0
  30. notslowapi/middleware/httpsredirect.py +3 -0
  31. notslowapi/middleware/trustedhost.py +3 -0
  32. notslowapi/middleware/wsgi.py +3 -0
  33. notslowapi/openapi/__init__.py +0 -0
  34. notslowapi/openapi/constants.py +3 -0
  35. notslowapi/openapi/docs.py +389 -0
  36. notslowapi/openapi/models.py +435 -0
  37. notslowapi/openapi/utils.py +679 -0
  38. notslowapi/param_functions.py +2460 -0
  39. notslowapi/params.py +754 -0
  40. notslowapi/py.typed +0 -0
  41. notslowapi/requests.py +2 -0
  42. notslowapi/responses.py +102 -0
  43. notslowapi/routing.py +6879 -0
  44. notslowapi/security/__init__.py +15 -0
  45. notslowapi/security/api_key.py +320 -0
  46. notslowapi/security/base.py +6 -0
  47. notslowapi/security/http.py +417 -0
  48. notslowapi/security/oauth2.py +693 -0
  49. notslowapi/security/open_id_connect_url.py +94 -0
  50. notslowapi/security/utils.py +7 -0
  51. notslowapi/sse.py +241 -0
  52. notslowapi/starlette/LICENSE.md +27 -0
  53. notslowapi/starlette/__init__.py +1 -0
  54. notslowapi/starlette/_exception_handler.py +105 -0
  55. notslowapi/starlette/_utils.py +160 -0
  56. notslowapi/starlette/applications.py +133 -0
  57. notslowapi/starlette/authentication.py +149 -0
  58. notslowapi/starlette/background.py +36 -0
  59. notslowapi/starlette/concurrency.py +59 -0
  60. notslowapi/starlette/config.py +140 -0
  61. notslowapi/starlette/convertors.py +89 -0
  62. notslowapi/starlette/datastructures.py +726 -0
  63. notslowapi/starlette/endpoints.py +127 -0
  64. notslowapi/starlette/exceptions.py +43 -0
  65. notslowapi/starlette/formparsers.py +301 -0
  66. notslowapi/starlette/middleware/__init__.py +37 -0
  67. notslowapi/starlette/middleware/authentication.py +52 -0
  68. notslowapi/starlette/middleware/base.py +244 -0
  69. notslowapi/starlette/middleware/body_limit.py +132 -0
  70. notslowapi/starlette/middleware/cors.py +179 -0
  71. notslowapi/starlette/middleware/errors.py +255 -0
  72. notslowapi/starlette/middleware/exception_handling.py +76 -0
  73. notslowapi/starlette/middleware/exceptions.py +67 -0
  74. notslowapi/starlette/middleware/gzip.py +222 -0
  75. notslowapi/starlette/middleware/httpsredirect.py +22 -0
  76. notslowapi/starlette/middleware/opentelemetry.py +116 -0
  77. notslowapi/starlette/middleware/sessions.py +134 -0
  78. notslowapi/starlette/middleware/trustedhost.py +66 -0
  79. notslowapi/starlette/middleware/wsgi.py +156 -0
  80. notslowapi/starlette/py.typed +0 -0
  81. notslowapi/starlette/requests.py +360 -0
  82. notslowapi/starlette/responses.py +593 -0
  83. notslowapi/starlette/routing.py +886 -0
  84. notslowapi/starlette/schemas.py +152 -0
  85. notslowapi/starlette/staticfiles.py +223 -0
  86. notslowapi/starlette/status.py +211 -0
  87. notslowapi/starlette/templating.py +156 -0
  88. notslowapi/starlette/testclient.py +558 -0
  89. notslowapi/starlette/types.py +26 -0
  90. notslowapi/starlette/websockets.py +202 -0
  91. notslowapi/staticfiles.py +1 -0
  92. notslowapi/templating.py +1 -0
  93. notslowapi/testclient.py +1 -0
  94. notslowapi/types.py +12 -0
  95. notslowapi/utils.py +136 -0
  96. notslowapi/websockets.py +3 -0
  97. notslowapi-0.1.0.dist-info/METADATA +163 -0
  98. notslowapi-0.1.0.dist-info/RECORD +102 -0
  99. notslowapi-0.1.0.dist-info/WHEEL +4 -0
  100. notslowapi-0.1.0.dist-info/entry_points.txt +5 -0
  101. notslowapi-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. notslowapi-0.1.0.dist-info/licenses/notslowapi/starlette/LICENSE.md +27 -0
@@ -0,0 +1,321 @@
1
+ ---
2
+ name: fastapi
3
+ description: FastAPI best practices and conventions. Use when working with FastAPI APIs, Pydantic models, dependencies, streaming responses including Server-Sent Events (SSE), and serving frontend apps. Keeps FastAPI code clean and up to date with the latest features and patterns.
4
+ ---
5
+
6
+ # FastAPI
7
+
8
+ Official FastAPI skill to write code with best practices, keeping up to date with new versions and features.
9
+
10
+ ## Quick Reference
11
+
12
+ * Serve frontend apps: use `app.frontend()` or `router.frontend()` for built frontend assets; see [Serve Frontend Apps](#serve-frontend-apps).
13
+ * Server-Sent Events (SSE): use `response_class=EventSourceResponse` and `yield`; see [Streaming](#streaming-json-lines-sse-bytes) and [the streaming reference](references/streaming.md).
14
+ * JSON Lines and byte streaming: see [the streaming reference](references/streaming.md).
15
+ * Dependencies: use `Annotated[..., Depends(...)]`; see [Dependency Injection](#dependency-injection) and [the dependency injection reference](references/dependencies.md) for `yield`, scopes, and class dependencies.
16
+ * Response models: prefer return types; use `response_model` when the public response schema differs from the internal return value; see [the response reference](references/responses.md).
17
+ * Pydantic models: do not use ellipsis or `RootModel`; see [the Pydantic reference](references/pydantic.md).
18
+ * Routing: declare router-level prefix, tags, and shared dependencies on the `APIRouter`; see [the path operation reference](references/path-operations.md).
19
+ * Tooling and related libraries: use uv, Ruff, ty, Asyncer, SQLModel, and HTTPX when applicable; see [the other tools reference](references/other-tools.md).
20
+
21
+ ## Use the `fastapi` CLI
22
+
23
+ Run the development server on localhost with reload:
24
+
25
+ ```bash
26
+ fastapi dev
27
+ ```
28
+
29
+ Run the production server:
30
+
31
+ ```bash
32
+ fastapi run
33
+ ```
34
+
35
+ Prefer declaring the entrypoint in `pyproject.toml`:
36
+
37
+ ```toml
38
+ [tool.fastapi]
39
+ entrypoint = "my_app.main:app"
40
+ ```
41
+
42
+ When adding the entrypoint is not possible, or the user explicitly asks not to, pass the app file path:
43
+
44
+ ```bash
45
+ fastapi dev my_app/main.py
46
+ ```
47
+
48
+ ## Use `Annotated`
49
+
50
+ Always prefer the `Annotated` style for parameter and dependency declarations. It keeps function signatures working in other contexts, respects the types, and allows reusability.
51
+
52
+ Use `Annotated` for parameter declarations, including `Path`, `Query`, `Header`, etc.:
53
+
54
+ ```python
55
+ from typing import Annotated
56
+
57
+ from fastapi import FastAPI, Path, Query
58
+
59
+ app = FastAPI()
60
+
61
+
62
+ @app.get("/items/{item_id}")
63
+ async def read_item(
64
+ item_id: Annotated[int, Path(ge=1, description="The item ID")],
65
+ q: Annotated[str | None, Query(max_length=50)] = None,
66
+ ):
67
+ return {"message": "Hello World"}
68
+ ```
69
+
70
+ Use `Annotated` for dependencies with `Depends()`. Unless asked not to, create a new type alias for the dependency to allow reusing it:
71
+
72
+ ```python
73
+ from typing import Annotated
74
+
75
+ from fastapi import Depends, FastAPI
76
+
77
+ app = FastAPI()
78
+
79
+
80
+ def get_current_user():
81
+ return {"username": "johndoe"}
82
+
83
+
84
+ CurrentUserDep = Annotated[dict, Depends(get_current_user)]
85
+
86
+
87
+ @app.get("/items/")
88
+ async def read_item(current_user: CurrentUserDep):
89
+ return {"message": "Hello World"}
90
+ ```
91
+
92
+ ## Do not use Ellipsis for *path operations* or Pydantic models
93
+
94
+ Do not use `...` as a default value for required parameters or model fields. It's not needed and not recommended.
95
+
96
+ ```python
97
+ from typing import Annotated
98
+
99
+ from fastapi import FastAPI, Query
100
+ from pydantic import BaseModel, Field
101
+
102
+ app = FastAPI()
103
+
104
+
105
+ class Item(BaseModel):
106
+ name: str
107
+ description: str | None = None
108
+ price: float = Field(gt=0)
109
+
110
+
111
+ @app.post("/items/")
112
+ async def create_item(item: Item, project_id: Annotated[int, Query()]):
113
+ return item
114
+ ```
115
+
116
+ See [the Pydantic reference](references/pydantic.md) for more details.
117
+
118
+ ## Return Type or Response Model
119
+
120
+ When possible, include a return type. It will be used to validate, filter, document, and serialize the response.
121
+
122
+ ```python
123
+ from fastapi import FastAPI
124
+ from pydantic import BaseModel
125
+
126
+ app = FastAPI()
127
+
128
+
129
+ class Item(BaseModel):
130
+ name: str
131
+ description: str | None = None
132
+
133
+
134
+ @app.get("/items/me")
135
+ async def get_item() -> Item:
136
+ return Item(name="Plumbus", description="All-purpose home device")
137
+ ```
138
+
139
+ Return types or response models filter data to avoid exposing sensitive information, and they let Pydantic serialize the data on the Rust side for performance.
140
+
141
+ Use `response_model` when the type you return is not the same as the public schema you want to validate, filter, document, and serialize. See [the response reference](references/responses.md).
142
+
143
+ ## Performance
144
+
145
+ Do not use `ORJSONResponse` or `UJSONResponse`, they are deprecated.
146
+
147
+ Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side.
148
+
149
+ ## Including Routers
150
+
151
+ When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in `include_router()`.
152
+
153
+ ```python
154
+ from fastapi import APIRouter, Depends, FastAPI
155
+
156
+ app = FastAPI()
157
+
158
+
159
+ def get_current_user():
160
+ return {"username": "johndoe"}
161
+
162
+
163
+ router = APIRouter(
164
+ prefix="/items",
165
+ tags=["items"],
166
+ dependencies=[Depends(get_current_user)],
167
+ )
168
+
169
+
170
+ @router.get("/")
171
+ async def list_items():
172
+ return []
173
+
174
+
175
+ app.include_router(router)
176
+ ```
177
+
178
+ See [the path operation reference](references/path-operations.md) for more routing patterns.
179
+
180
+ ## Serve Frontend Apps
181
+
182
+ Use `app.frontend()` to serve a built static frontend app, for example a directory generated by Vite, Astro, Angular, Svelte, Vue, or a similar tool.
183
+
184
+ ```python
185
+ from fastapi import FastAPI
186
+
187
+ app = FastAPI()
188
+
189
+ app.frontend("/", directory="dist")
190
+ ```
191
+
192
+ Use `router.frontend()` when the frontend belongs to an `APIRouter`; normal router prefix behavior applies when the router is included.
193
+
194
+ ```python
195
+ from fastapi import APIRouter, FastAPI
196
+
197
+ app = FastAPI()
198
+ router = APIRouter(prefix="/admin")
199
+
200
+ router.frontend("/", directory="admin-dist")
201
+ app.include_router(router)
202
+ ```
203
+
204
+ `app.frontend()` and `router.frontend()` are low-priority routes: regular API routes are matched first, then frontend files and client-side routing fallbacks. Use this for single-page apps and built frontend assets instead of mounting `StaticFiles` manually.
205
+
206
+ ## Dependency Injection
207
+
208
+ Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup with `yield`, or is shared across endpoints.
209
+
210
+ Apply shared dependencies at the router level via `dependencies=[Depends(...)]`.
211
+
212
+ See [the dependency injection reference](references/dependencies.md) for detailed patterns including `yield` with `scope`, and class dependencies.
213
+
214
+ ## Async vs Sync *path operations*
215
+
216
+ Use `async` *path operations* only when fully certain that the logic called inside is compatible with async and await, and that it doesn't block.
217
+
218
+ ```python
219
+ from fastapi import FastAPI
220
+
221
+ app = FastAPI()
222
+
223
+
224
+ @app.get("/async-items/")
225
+ async def read_async_items():
226
+ data = await some_async_library.fetch_items()
227
+ return data
228
+
229
+
230
+ @app.get("/items/")
231
+ def read_items():
232
+ data = some_blocking_library.fetch_items()
233
+ return data
234
+ ```
235
+
236
+ In case of doubt, or by default, use regular `def` functions. They will be run in a threadpool so they don't block the event loop. The same rules apply to dependencies.
237
+
238
+ Make sure blocking code is not run inside of `async` functions. The logic will work, but will damage performance heavily.
239
+
240
+ When needing to mix blocking and async code, see Asyncer in [the other tools reference](references/other-tools.md).
241
+
242
+ ## Streaming (JSON Lines, SSE, bytes)
243
+
244
+ To stream Server-Sent Events, use `response_class=EventSourceResponse` and `yield` items from the endpoint.
245
+
246
+ ```python
247
+ from collections.abc import AsyncIterable
248
+
249
+ from fastapi import FastAPI
250
+ from fastapi.sse import EventSourceResponse, ServerSentEvent
251
+
252
+ app = FastAPI()
253
+
254
+
255
+ @app.get("/events", response_class=EventSourceResponse)
256
+ async def stream_events() -> AsyncIterable[ServerSentEvent]:
257
+ yield ServerSentEvent(data={"status": "started"}, event="status", id="1")
258
+ ```
259
+
260
+ Plain objects are automatically JSON-serialized as `data:` fields. Use `ServerSentEvent` for full control over SSE fields (`event`, `id`, `retry`, `comment`) and `raw_data` for pre-formatted strings.
261
+
262
+ See [the streaming reference](references/streaming.md) for JSON Lines, Server-Sent Events (`EventSourceResponse`, `ServerSentEvent`), and byte streaming (`StreamingResponse`) patterns.
263
+
264
+ ## Tooling
265
+
266
+ See [the other tools reference](references/other-tools.md) for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.
267
+
268
+ ## Other Libraries
269
+
270
+ See [the other tools reference](references/other-tools.md) for details on other libraries:
271
+
272
+ * Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio.
273
+ * SQLModel for working with SQL databases, prefer it over SQLAlchemy.
274
+ * HTTPX for interacting with HTTP (other APIs), prefer it over Requests.
275
+
276
+ ## Do not use Pydantic RootModels
277
+
278
+ Do not use Pydantic `RootModel`; instead use regular type annotations with `Annotated` and Pydantic validation utilities.
279
+
280
+ ```python
281
+ from typing import Annotated
282
+
283
+ from fastapi import Body, FastAPI
284
+ from pydantic import Field
285
+
286
+ app = FastAPI()
287
+
288
+
289
+ @app.post("/items/")
290
+ async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):
291
+ return items
292
+ ```
293
+
294
+ FastAPI supports these type annotations and will create a Pydantic `TypeAdapter` for them, so types work normally without custom wrapper models. See [the Pydantic reference](references/pydantic.md).
295
+
296
+ ## Use one HTTP operation per function
297
+
298
+ Don't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code.
299
+
300
+ ```python
301
+ from fastapi import FastAPI
302
+ from pydantic import BaseModel
303
+
304
+ app = FastAPI()
305
+
306
+
307
+ class Item(BaseModel):
308
+ name: str
309
+
310
+
311
+ @app.get("/items/")
312
+ async def list_items():
313
+ return []
314
+
315
+
316
+ @app.post("/items/")
317
+ async def create_item(item: Item):
318
+ return item
319
+ ```
320
+
321
+ See [the path operation reference](references/path-operations.md) for more examples.
@@ -0,0 +1,142 @@
1
+ # Dependency Injection
2
+
3
+ Use dependencies when:
4
+
5
+ * They can't be declared in Pydantic validation and require additional logic
6
+ * The logic depends on external resources or could block in any other way
7
+ * Other dependencies need their results (it's a sub-dependency)
8
+ * The logic can be shared by multiple endpoints to do things like error early, handle authentication, etc.
9
+ * They need to handle cleanup (e.g., DB sessions, file handles), using dependencies with `yield`
10
+ * Their logic needs input data from the request, like headers, query parameters, etc.
11
+
12
+ ## Dependencies with `yield` and `scope`
13
+
14
+ When using dependencies with `yield`, they can have a `scope` that defines when the exit code is run.
15
+
16
+ Use the default scope `"request"` to run the exit code after the response is sent back.
17
+
18
+ ```python
19
+ from typing import Annotated
20
+
21
+ from fastapi import Depends, FastAPI
22
+
23
+ app = FastAPI()
24
+
25
+
26
+ def get_db():
27
+ db = DBSession()
28
+ try:
29
+ yield db
30
+ finally:
31
+ db.close()
32
+
33
+
34
+ DBDep = Annotated[DBSession, Depends(get_db)]
35
+
36
+
37
+ @app.get("/items/")
38
+ async def read_items(db: DBDep):
39
+ return db.query(Item).all()
40
+ ```
41
+
42
+ Use the scope `"function"` when they should run the exit code after the response data is generated but before the response is sent back to the client.
43
+
44
+ ```python
45
+ from typing import Annotated
46
+
47
+ from fastapi import Depends, FastAPI
48
+
49
+ app = FastAPI()
50
+
51
+
52
+ def get_username():
53
+ try:
54
+ yield "Rick"
55
+ finally:
56
+ print("Clean up before response is sent")
57
+
58
+ UserNameDep = Annotated[str, Depends(get_username, scope="function")]
59
+
60
+ @app.get("/users/me")
61
+ def get_user_me(username: UserNameDep):
62
+ return username
63
+ ```
64
+
65
+ ## Class Dependencies
66
+
67
+ Avoid creating class dependencies when possible.
68
+
69
+ If a class is needed, instead create a regular function dependency that returns a class instance.
70
+
71
+ Do this:
72
+
73
+ ```python
74
+ from dataclasses import dataclass
75
+ from typing import Annotated
76
+
77
+ from fastapi import Depends, FastAPI
78
+
79
+ app = FastAPI()
80
+
81
+
82
+ @dataclass
83
+ class DatabasePaginator:
84
+ offset: int = 0
85
+ limit: int = 100
86
+ q: str | None = None
87
+
88
+ def get_page(self) -> dict:
89
+ # Simulate a page of data
90
+ return {
91
+ "offset": self.offset,
92
+ "limit": self.limit,
93
+ "q": self.q,
94
+ "items": [],
95
+ }
96
+
97
+
98
+ def get_db_paginator(
99
+ offset: int = 0, limit: int = 100, q: str | None = None
100
+ ) -> DatabasePaginator:
101
+ return DatabasePaginator(offset=offset, limit=limit, q=q)
102
+
103
+
104
+ PaginatorDep = Annotated[DatabasePaginator, Depends(get_db_paginator)]
105
+
106
+
107
+ @app.get("/items/")
108
+ async def read_items(paginator: PaginatorDep):
109
+ return paginator.get_page()
110
+ ```
111
+
112
+ instead of this:
113
+
114
+ ```python
115
+ # DO NOT DO THIS
116
+ from typing import Annotated
117
+
118
+ from fastapi import Depends, FastAPI
119
+
120
+ app = FastAPI()
121
+
122
+
123
+ class DatabasePaginator:
124
+ def __init__(self, offset: int = 0, limit: int = 100, q: str | None = None):
125
+ self.offset = offset
126
+ self.limit = limit
127
+ self.q = q
128
+
129
+ def get_page(self) -> dict:
130
+ # Simulate a page of data
131
+ return {
132
+ "offset": self.offset,
133
+ "limit": self.limit,
134
+ "q": self.q,
135
+ "items": [],
136
+ }
137
+
138
+
139
+ @app.get("/items/")
140
+ async def read_items(paginator: Annotated[DatabasePaginator, Depends()]):
141
+ return paginator.get_page()
142
+ ```
@@ -0,0 +1,76 @@
1
+ # Other Tools
2
+
3
+ ## uv
4
+
5
+ If uv is available, use it to manage dependencies.
6
+
7
+ ## Ruff
8
+
9
+ If Ruff is available, use it to lint and format the code. Consider enabling the FastAPI rules.
10
+
11
+ ## ty
12
+
13
+ If ty is available, use it to check types.
14
+
15
+ ## Asyncer
16
+
17
+ When needing to run blocking code inside of async functions, or async code inside of blocking functions, suggest using Asyncer.
18
+
19
+ Prefer it over AnyIO or asyncio.
20
+
21
+ Install:
22
+
23
+ ```bash
24
+ uv add asyncer
25
+ ```
26
+
27
+ Run blocking sync code inside of async with `asyncify()`:
28
+
29
+ ```python
30
+ from asyncer import asyncify
31
+ from fastapi import FastAPI
32
+
33
+ app = FastAPI()
34
+
35
+
36
+ def do_blocking_work(name: str) -> str:
37
+ # Some blocking I/O operation
38
+ return f"Hello {name}"
39
+
40
+
41
+ @app.get("/items/")
42
+ async def read_items():
43
+ result = await asyncify(do_blocking_work)(name="World")
44
+ return {"message": result}
45
+ ```
46
+
47
+ And run async code inside of blocking sync code with `syncify()`:
48
+
49
+ ```python
50
+ from asyncer import syncify
51
+ from fastapi import FastAPI
52
+
53
+ app = FastAPI()
54
+
55
+
56
+ async def do_async_work(name: str) -> str:
57
+ return f"Hello {name}"
58
+
59
+
60
+ @app.get("/items/")
61
+ def read_items():
62
+ result = syncify(do_async_work)(name="World")
63
+ return {"message": result}
64
+ ```
65
+
66
+ ## SQLModel for SQL databases
67
+
68
+ When working with SQL databases, prefer using SQLModel as it is integrated with Pydantic and will allow declaring data validation with the same models.
69
+
70
+ Prefer it over SQLAlchemy.
71
+
72
+ ## HTTPX
73
+
74
+ Use HTTPX for handling HTTP communication (e.g. with other APIs). It supports sync and async usage.
75
+
76
+ Prefer it over Requests.
@@ -0,0 +1,93 @@
1
+ # Path Operations and Routing
2
+
3
+ ## Including Routers
4
+
5
+ When declaring routers, prefer to add router-level parameters like prefix, tags, and shared dependencies to the router itself instead of in `include_router()`.
6
+
7
+ Do this:
8
+
9
+ ```python
10
+ from fastapi import APIRouter, FastAPI
11
+
12
+ app = FastAPI()
13
+
14
+ router = APIRouter(prefix="/items", tags=["items"])
15
+
16
+
17
+ @router.get("/")
18
+ async def list_items():
19
+ return []
20
+
21
+
22
+ app.include_router(router)
23
+ ```
24
+
25
+ Instead of:
26
+
27
+ ```python
28
+ # DO NOT DO THIS
29
+ from fastapi import APIRouter, FastAPI
30
+
31
+ app = FastAPI()
32
+
33
+ router = APIRouter()
34
+
35
+
36
+ @router.get("/")
37
+ async def list_items():
38
+ return []
39
+
40
+
41
+ app.include_router(router, prefix="/items", tags=["items"])
42
+ ```
43
+
44
+ There could be exceptions, but try to follow this convention.
45
+
46
+ Apply shared dependencies at the router level via `dependencies=[Depends(...)]`.
47
+
48
+ ## Use one HTTP operation per function
49
+
50
+ Don't mix HTTP operations in a single function. Having one function per HTTP operation helps separate concerns and organize the code.
51
+
52
+ Do this:
53
+
54
+ ```python
55
+ from fastapi import FastAPI
56
+ from pydantic import BaseModel
57
+
58
+ app = FastAPI()
59
+
60
+
61
+ class Item(BaseModel):
62
+ name: str
63
+
64
+
65
+ @app.get("/items/")
66
+ async def list_items():
67
+ return []
68
+
69
+
70
+ @app.post("/items/")
71
+ async def create_item(item: Item):
72
+ return item
73
+ ```
74
+
75
+ Instead of:
76
+
77
+ ```python
78
+ # DO NOT DO THIS
79
+ from fastapi import FastAPI, Request
80
+ from pydantic import BaseModel
81
+
82
+ app = FastAPI()
83
+
84
+
85
+ class Item(BaseModel):
86
+ name: str
87
+
88
+
89
+ @app.api_route("/items/", methods=["GET", "POST"])
90
+ async def handle_items(request: Request):
91
+ if request.method == "GET":
92
+ return []
93
+ ```