FastAPI

v2026.09.24

This skill should be used when the user asks about "FastAPI", "FastAPI routes", "FastAPI dependencies", "Pydantic models", "FastAPI middleware", "API endpoints", "OpenAPI", or mentions FastAPI development.

GitHub
Install command
npx skhub add eyadsibai/fastapi
Markdown
SKILL.md

FastAPI Development

Guidance for building APIs with FastAPI following best practices.


Core Concepts

Route Decorators

DecoratorHTTP MethodUse Case
@app.get()GETRetrieve data
@app.post()POSTCreate resource
@app.put()PUTFull update
@app.patch()PATCHPartial update
@app.delete()DELETERemove resource

Response Status Codes

CodeMeaningWhen to Use
200OKSuccessful GET/PUT/PATCH
201CreatedSuccessful POST
204No ContentSuccessful DELETE
400Bad RequestInvalid input
401UnauthorizedAuthentication required
403ForbiddenNo permission
404Not FoundResource doesn't exist
422UnprocessableValidation failed

Dependency Injection

Key concept: Dependencies are functions that FastAPI calls before your route handler. Use yield for cleanup logic.

PatternUse Case
Simple functionGet config, compute values
Generator (yield)Database sessions, connections
Class-basedComplex dependencies with state
Nested dependenciesDependencies that depend on other dependencies

Common Dependencies

DependencyPurpose
get_dbDatabase session (yield for cleanup)
get_current_userAuthentication + user retrieval
get_settingsConfiguration singleton
rate_limiterRequest throttling

Key concept: Use Annotated[Type, Depends(func)] for cleaner type hints and reusability.


Pydantic Models

Model Patterns

PatternPurpose
Base modelShared fields
Create modelInput for POST (no id)
Update modelPartial updates (all Optional)
Response modelOutput (includes id, timestamps)
DB modelInternal with from_attributes = True

Validation Features

FeaturePurpose
Field(...)Required with constraints
Field(default=...)Optional with default
field_validatorCustom validation logic
model_validatorCross-field validation
pattern=Regex validation
ge=, le=Numeric bounds
min_length=, max_length=String/list length

Error Handling

ApproachUse Case
HTTPExceptionSimple errors with status code
Custom exception classStructured error responses
@app.exception_handlerGlobal error handling
RequestValidationErrorCustomize validation errors

Key concept: Create custom exception classes for consistent error response format across your API.


Router Organization

ConceptPurpose
APIRouterGroup related endpoints
prefixURL prefix for all routes
tagsOpenAPI documentation grouping
dependenciesRouter-level dependencies

Project Structure

DirectoryContents
routers/Route handlers by domain
models/SQLAlchemy/database models
schemas/Pydantic request/response models
services/Business logic
dependencies.pyShared dependencies
config.pySettings and configuration

Background Tasks

MethodUse Case
BackgroundTasksSimple async tasks (email, logging)
CeleryHeavy tasks, retries, scheduling
ARQAsync Redis queue

Key concept: BackgroundTasks run after response is sent—good for non-critical operations that shouldn't block the response.


Testing Patterns

ClientUse Case
TestClientSync tests (most common)
AsyncClient (httpx)Async tests, lifespan events

Dependency Override Pattern

  1. Create test version of dependency
  2. Set app.dependency_overrides[original] = test_version
  3. Run tests
  4. Clear overrides after

Key concept: Override get_db for test database, get_current_user for auth bypass.


Best Practices

PracticeWhy
Use response_modelControl output, hide internal fields
Use dependency injectionTestable, reusable code
Separate schemas from DB modelsDecouple API from database
Use routers for organizationMaintainable as API grows
Add OpenAPI descriptionsSelf-documenting API
Use async for I/OBetter concurrency

Resources

Discovery
Tags

No tags published for this skill.

Version
Latest version metadata

Version

v2026.09.24

Published

Sep 24, 2026

Category

Uncategorized

License

Not specified

Source path

plugins/ltk-engineering/skills/python/fastapi

Default branch

master

Latest commit

f8e8569

Tree SHA

8bcd589