{"dataset":{"id":"00000000-0000-0000-0000-000000000024","slug":"fastapi-best-practices","name":"FastAPI best practices","description":"Source-linked guidance on FastAPI fundamentals: typed path parameters and Pydantic validation, dependency injection with Depends, async path operations, response models, and error handling with HTTPException. Scoped to FastAPI; not a general Python web corpus.","visibility":"public","version":1,"documentCount":5,"publisher":"Koskamo editorial","license":"Original summaries; linked sources retain their own terms.","reviewedAt":"2026-10-04T00:00:00.000Z","readOnly":true,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},"total":5,"documents":[{"title":"Error handling with HTTPException","sourceUrl":"https://fastapi.tiangolo.com/tutorial/handling-errors/","text":"To return HTTP error responses to the client, raise HTTPException — imported from fastapi — rather than returning it: it is a normal Python exception with additional data relevant for APIs, as in raise HTTPException(status_code=404, detail=\"Item not found\"). Raising from anywhere in the call chain, including a utility function called by the path operation, terminates that request right away and sends the error to the client without running the rest of the path operation code. The detail parameter accepts any value that can be converted to JSON — not only str, but dict and list — and FastAPI handles the conversion automatically. When an error needs custom headers, for example for some types of security, pass headers={\"X-Error\": \"There goes my error\"}; the tutorial notes you probably won't need this directly in everyday code. For exceptions of your own, install a global custom exception handler with @app.exception_handler(), using the same exception utilities from Starlette, and return a JSONResponse. Scope: FastAPI. Reviewed October 4, 2026.","id":"fastapi-best-practices:Error handling with HTTPException","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Response models filter output data","sourceUrl":"https://fastapi.tiangolo.com/tutorial/response-model/","text":"Declare a return type on each path operation, such as -> list[Item], and FastAPI uses it to validate the returned data — invalid output means your app code is broken, so it returns a server error instead of incorrect data — to add a JSON Schema for the response to the OpenAPI path operation, feeding the automatic docs and client code generation tools, to serialize the result to JSON with Pydantic, and, most importantly, to limit and filter the output data to what the type defines, which is particularly important for security. When you must return data that does not exactly match the declared type — a dictionary or database object declared as a Pydantic model — use the path operation decorator's response_model parameter instead of the return type annotation; it works in @app.get(), @app.post(), @app.put(), @app.delete(), and the other path operations. Never store or return a plain user password; the tutorial's fix is an input model (UserIn) carrying the password and a separate output model (UserOut) without it. Scope: FastAPI. Reviewed October 4, 2026.","id":"fastapi-best-practices:Response models filter output data","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Async path operations: def vs async def","sourceUrl":"https://fastapi.tiangolo.com/async/","text":"Declare path operation functions with async def when you use third-party libraries that must be called with await, because await is only valid inside functions created with async def. If a library that communicates with a database, an API, or the file system has no await support — currently the case for most database libraries — declare the path operation with plain def instead. If your application does not have to communicate with anything else and wait for it to respond, use async def even without await inside; if you just don't know, use normal def. You can mix def and async def path operations as much as you need: FastAPI will do the right thing with each, work asynchronously either way, and be extremely fast, but following these rules lets it apply some performance optimizations. The waiting this manages is normally I/O-bound work such as network transfers, disk reads, or database operations. Scope: FastAPI. Reviewed October 4, 2026.","id":"fastapi-best-practices:Async path operations: def vs async def","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Dependency injection with Depends","sourceUrl":"https://fastapi.tiangolo.com/tutorial/dependencies/","text":"Dependency injection means your path operation functions declare the things they require to work — \"dependencies\" — and FastAPI takes care of doing whatever is needed to provide them. This is useful for shared logic, sharing database connections, and enforcing security, authentication, and role requirements, all while minimizing code repetition. A dependency, or \"dependable\", is just a function that can take all the same parameters a path operation function can take, such as async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100). Declare use of it by importing Depends from fastapi and annotating a parameter, as in commons: Annotated[dict, Depends(common_parameters)]; the same dependency can serve several path operations, as the tutorial does for /items/ and /users/. Keep each dependency small and single-purpose so they compose cleanly — that preference is Koskamo editorial guidance. Scope: FastAPI. Reviewed October 4, 2026.","id":"fastapi-best-practices:Dependency injection with Depends","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"},{"title":"Path parameters with typed Pydantic validation","sourceUrl":"https://fastapi.tiangolo.com/tutorial/path-params/","text":"Declare the type of a path parameter with standard Python type annotations, as in async def read_item(item_id: int); that single declaration gives editor support with error checks and completion, automatic request parsing (the function receives the integer 3, not the string \"3\"), and data validation — a request for /items/foo returns a clear HTTP error stating exactly where validation failed, and the same error appears for a float such as /items/4.2. The same declaration also produces automatic, interactive API documentation integrating Swagger UI, and because the generated schema follows the OpenAPI standard, FastAPI ships alternative documentation with ReDoc, plus many compatible tools including code generation for many languages. All data validation is performed under the hood by Pydantic, and the same declarations work with str, float, bool, and many other complex data types. Order matters: path operations are evaluated in order, so declare a fixed path like /users/me before /users/{user_id}. Scope: FastAPI. Reviewed October 4, 2026.","id":"fastapi-best-practices:Path parameters with typed Pydantic validation","version":1,"createdAt":"2026-10-04T00:00:00.000Z","updatedAt":"2026-10-04T00:00:00.000Z"}]}