Fastapi best practices
Skill dkmqflx/fastapi-best-practices-plugin/plugins/fastapi-best-practices/skills/fastapi-best-practices
Claude Code plugin: FastAPI best practices (41 rules, 13 categories) grounded in the official FastAPI docs
npx -y skills add dkmqflx/fastapi-best-practices-plugin --skill fastapi-best-practicesAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
What its author says it does
Copied from the file, not written here
Use when writing, reviewing, or refactoring FastAPI code — endpoints, APIRouter, query/path parameters, dependencies (Depends), Pydantic request/response models, error handling, async def vs def, lifespan events, streaming, background tasks, settings, middleware, or CORS. Triggers on FastAPI backend work, route design, or API code review. For auth/security see fastapi-security; for tests see fastapi-testing.
The file declares its own license as MIT. That is the author’s claim about this one file, and it is not the same thing as the license GitHub reports for the repository, which is listed with the other numbers below.
SKILL.md
5.9 KB, ~1.4k tokens by cl100k_base, as published. Nobody here has run it
FastAPI Best Practices
Reference guide for writing FastAPI code that follows the official documentation (https://fastapi.tiangolo.com/). 33 rules across 11 categories, prioritized by impact — correctness first, structure/validation next, performance and polish last. Each rule pairs an incorrect example with the official correct pattern and links the relevant docs page.
Security/authentication and testing are covered by two companion skills —
fastapi-security and fastapi-testing — since they tend to live in their own
files (auth modules, test suites) rather than alongside routing/model code.
When to Apply
Reference these guidelines when:
- Writing new FastAPI endpoints, routers, parameters, or Pydantic models
- Designing dependency injection or error handling
- Adding streaming, background tasks, settings/config, or middleware
- Reviewing or refactoring a FastAPI backend
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Request/Response Models | CRITICAL | model- |
| 2 | Request Parameters & Validation | HIGH | params- |
| 3 | App Structure & Routing | HIGH | structure- |
| 4 | Dependency Injection | HIGH | di- |
| 5 | Error Handling | HIGH | error- |
| 6 | Async & Concurrency | MEDIUM | async- |
| 7 | Responses & Streaming | MEDIUM | response- |
| 8 | Background Tasks & Config | MEDIUM | background-, config- |
| 9 | Lifespan & Resources | MEDIUM | lifespan- |
| 10 | Middleware & Cross-cutting | MEDIUM | mw- |
| 11 | OpenAPI Documentation | LOW | docs- |
Quick Reference
1. Request/Response Models (CRITICAL)
model-response-model— declare a response model on every endpointmodel-separate-input-output— separate input vs output models so secrets never leakmodel-return-type-annotation— prefer the return-type annotation; useresponse_model=only when types differmodel-pydantic-validation— validate with PydanticField/Literal, not manualifchecksmodel-exclude-unset—response_model_exclude_unsetfor partial/sparse data
2. Request Parameters & Validation (HIGH)
params-query-validation— validate query params withAnnotated[..., Query()]params-path-validation— constrain path params withAnnotated[..., Path()](ge/le)params-query-param-models— group filter/sort/search params in a Pydantic query modelparams-pagination— paginate lists with boundedlimit/offset; empty list, not 404
3. App Structure & Routing (HIGH)
structure-apirouter-prefix-tags— give eachAPIRouteraprefixandtagsstructure-bigger-app-layout— split intorouters/,models/,dependencies.pystructure-import-submodule— import the submodule, not theroutervariablestructure-status-code-decorator— set the successstatus_codein the decorator (201 for creation)
4. Dependency Injection (HIGH)
di-use-depends— share logic viaDepends(), not manual instantiationdi-annotated— useAnnotated[T, Depends(...)]over the legacy default-value formdi-reusable-type-alias— hoist repeated dependencies into a type aliasdi-yield-cleanup— useyielddependencies for setup/teardown (DB sessions, files)
5. Error Handling (HIGH)
error-raise-httpexception—raise HTTPException, neverreturnan errorerror-specific-status-codes— use specific codes (404/400/409), not a blanket 500error-reraise-httpexception— re-raiseHTTPExceptionin broadexceptblockserror-custom-handler— centralize cross-cutting errors in@app.exception_handler
6. Async & Concurrency (MEDIUM)
async-def-vs-def— chooseasync defvsdefby the library you callasync-no-blocking-in-async— never call blocking code insideasync defasync-await-all-io—awaitevery async call
7. Responses & Streaming (MEDIUM)
response-streaming— stream long/LLM responses withStreamingResponse, not bufferingresponse-additional-responses— document non-200 responses in OpenAPI
8. Background Tasks & Config (MEDIUM)
background-tasks— useBackgroundTasksfor post-response workconfig-pydantic-settings— read config from env withpydantic-settings+@lru_cache
9. Lifespan & Resources (MEDIUM)
lifespan-context-manager— use thelifespancontext manager, not deprecated@app.on_eventlifespan-load-once— load expensive resources (models, indexes) once at startup
10. Middleware & Cross-cutting (MEDIUM)
mw-cors— configureCORSMiddlewarewith an explicit origin allowlistmw-custom-http— add timing/request-id/logging via@app.middleware("http")
11. OpenAPI Documentation (LOW)
docs-openapi-metadata— addsummary,description,tags,response_description
How to Use
Read the individual rule file for the detailed explanation and before/after example:
rules/model-separate-input-output.md
rules/params-query-param-models.md
rules/di-yield-cleanup.md
rules/error-custom-handler.md
Each rule file contains:
- A short explanation of why it matters, tied to the official docs
- An Incorrect example (the antipattern)
- A Correct example (the official pattern)
- A link to the relevant page on https://fastapi.tiangolo.com/
All examples follow the official FastAPI documentation and avoid deprecated APIs.