← スキル一覧に戻る

fastapi-stack-development
by Qredence
⭐ 1🍴 1📅 2026年1月23日
SKILL.md
name: FastAPI Stack Development description: Comprehensive guidance for FastAPI, Typer, and SQLModel development including patterns, best practices, API design, CLI development, database integration, testing, and common workflows. Use this skill when building applications with any of these frameworks.
FastAPI Stack Development Skill
This skill provides guidance for the FastAPI ecosystem: FastAPI (web APIs), Typer (CLI tools), and SQLModel (database models). All three frameworks share common patterns and work seamlessly together.
When to Use This Skill
Load this skill when you are:
- Building FastAPI applications and REST APIs
- Creating Typer CLI tools and utilities
- Designing SQLModel database schemas and queries
- Developing applications combining these technologies
- Refactoring or debugging FastAPI stack code
- Setting up new projects with this stack
Unload this skill when you're done with FastAPI/CLI/DB work to free up context.
FastAPI Core Concepts
Application Structure
- Organize routes into routers by domain or feature
- Use dependencies for shared logic (auth, DB sessions, config)
- Separate business logic from route handlers (service layer)
- Keep
main.pyminimal - import and include routers
Pydantic Models & Validation
- Use Pydantic models for request/response bodies
- Leverage field validators for complex validation
- Separate request models from response models
- Use
Field()for metadata (examples, constraints, descriptions) - Consider using
BaseModelvsSQLModelappropriately
Dependency Injection
- Use
Depends()for injectable components - Create reusable dependencies (auth, caching, rate limiting)
- Use
yieldfor resource cleanup (DB sessions, files) - Cache dependencies with
use_cache=True(default) oruse_cache=False
Async/Await & Performance
- Use
async deffor I/O-bound operations (DB queries, HTTP requests) - Use
deffor CPU-bound operations or when not async-ready - Database: Use
AsyncSessionfor async drivers (asyncpg, aiomysql) - Background tasks with
BackgroundTasksfor fire-and-forget operations
Middleware & Security
- Add middleware for CORS, logging, compression
- Implement security: OAuth2 scopes, API keys, JWT
- Use
fastapi.securityutilities for auth schemes - Validate origins in production for CORS
Typer CLI Development
Command Structure
- Use
typer.Typer()for the main app instance - Create subcommands with
@app.command()or separate apps withapp.add_typer() - Use
app.callback()for global options and setup - Group related commands logically
Arguments & Options
- Use arguments for required positional inputs
- Use options for optional parameters with defaults
- Leverage rich types (Path, File, enums) for automatic validation
- Use
richintegration for formatted output (tables, panels, progress)
Testing CLI
- Use
CliRunnerfromtyper.testingfor unit tests - Test happy paths, error cases, and validation
- Mock external dependencies (API calls, DB operations)
Integration with FastAPI
- Share Pydantic models between API and CLI
- Use CLI for admin tasks (seed DB, migrations, diagnostics)
- Reuse service layer logic between endpoints and commands
SQLModel Database Patterns
Model Design
- Use
SQLModelfor tables that map to database - Use
Field()for DB constraints (primary_key, index, unique) - Define relationships with back_populates
- Use
Field(default=None)for nullable columns - Separate read/write models with
Field(exclude=True)or separate classes
Session Management
- Use
sessionmakerfor DB session factory - Async: Use
async_sessionmakerwithAsyncSession - Use
yieldin dependencies for automatic cleanup - Always commit or rollback explicitly
Query Patterns
- Use
select(Model).where(Model.field == value)for filtering - Chain
.where()conditions with&and| - Use
.limit()and.offset()for pagination - Eager load relationships with
.selectinload()or.joinedload() - Use
.exec()for queries,.scalar_one_or_none()for single results
Migrations
- Use Alembic for schema migrations
- Generate migration with
alembic revision --autogenerate - Review generated migrations before applying
- Test migrations on a staging database first
Integration Patterns
FastAPI + SQLModel
- Create DB dependency that yields a session
- Pass session to service layer, not route handlers
- Use
response_model=to document output types - Return Pydantic models directly from endpoints
Typer + FastAPI
- Share models between
models/directory - CLI commands can import FastAPI services
- Use CLI for health checks, data imports, admin tasks
Pydantic Model Reuse
- Create base models in
models/base.py - Use inheritance for request/response variants
- Keep models in
models/separate from routes - Consider using
TypeAdapterfor validation outside APIs
Configuration Management
- Use
pydantic-settingsfor environment-based config - Share config instance across FastAPI and Typer
- Validate config at startup with Pydantic
- Document environment variables in README
Project Structure
Recommended Layout
project/
├── alembic/ # Database migrations
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app instance
│ ├── cli.py # Typer CLI app
│ ├── config.py # Pydantic settings
│ ├── models/ # SQLModel models
│ ├── schemas/ # Request/response models
│ ├── api/ # FastAPI routers
│ ├── services/ # Business logic
│ ├── db/ # Database utilities
│ └── utils/ # Shared utilities
├── tests/
└── requirements.txt # or pyproject.toml
Separation of Concerns
- Routes: HTTP request/response handling only
- Services: Business logic and orchestration
- Models: Data structures and database schemas
- Utils: Pure functions and helpers
Test Organization
- Mirror source structure in
tests/ - Unit tests for services and utilities
- Integration tests for API endpoints
- Use
pytestandhttpx.AsyncClientfor FastAPI testing
Common Workflows
Setting Up a New Project
- Create virtual environment and install dependencies
- Initialize FastAPI app in
main.py - Set up
pydantic-settingsinconfig.py - Create SQLModel models in
models/ - Configure Alembic for migrations
- Create Typer CLI in
cli.py - Set up test fixtures and tests
Adding Authentication
- Install
python-joseandpasslibfor JWT - Create auth dependency with
Depends() - Add login endpoint that returns JWT token
- Protect routes with
Depends(get_current_user) - Add optional OAuth2 scopes for fine-grained access
Creating Admin CLI Commands
- Add command in
cli.pywith@app.command() - Import models and services from
app/ - Add rich output for better UX
- Add tests with
CliRunner - Document in
--helptext
Database Migrations
- Create Alembic config with
alembic init - Set
sqlalchemy.urlinalembic.ini - Generate migration with
autogenerate - Review and edit migration script
- Apply with
alembic upgrade head - Add rollback with
alembic downgrade -1
Testing Strategies
- Unit tests: Mock DB and external services
- Integration tests: Use test database, real sessions
- FastAPI: Use
httpx.AsyncClientwith test app - Typer: Use
CliRunnerwith test runner - Use pytest fixtures for common setup (DB, client, auth)
Best Practices
Type Hints Across Frameworks
- Always annotate function signatures
- Use
typing.Optionalfor nullable fields - Use
typing.List[Model]orlist[Model]for collections - Leverage Pydantic for runtime type checking
- Run
mypyorpyrightfor static type checking
Validation & Error Handling
- Use Pydantic for request validation (automatic)
- Return
HTTPExceptionfor expected errors - Use custom exception handlers for consistent responses
- Log errors with context (request ID, user ID, params)
- Never expose stack traces in production
Documentation
- API: OpenAPI/Swagger at
/docsauto-generated - Add
description=to endpoints for better docs - Add examples to Pydantic fields
- CLI: Use
help=on arguments and options - Keep README up-to-date with setup and usage
Async vs Sync Patterns
- Database: Prefer
AsyncSessionwith async drivers - External APIs: Use
httpx.AsyncClient - File I/O: Use
aiofilesfor async operations - CPU-bound: Use
run_in_executor()if needed
Performance Optimization
- Use response compression middleware
- Cache expensive operations with
functools.lru_cacheor Redis - Use database indexes properly
- Eager load relationships to avoid N+1 queries
- Implement rate limiting on public endpoints
Security Considerations
- Validate all inputs (Pydantic handles this)
- Sanitize user input for queries (SQLModel parameterized)
- Use HTTPS in production
- Implement rate limiting on auth endpoints
- Regularly update dependencies
- Use secrets management for API keys and passwords
Progressive Disclosure
When working with this skill:
- Start with SKILL.md - this gives you the core concepts and patterns
- Only load additional reference docs when you hit a specific problem
- Focus on the relevant section (FastAPI, Typer, or SQLModel) based on your current task
- Refer back to project structure and best practices when refactoring
Reference Resources
スコア
総合スコア
60/100
リポジトリの品質指標に基づく評価
✓SKILL.md
SKILL.mdファイルが含まれている
+20
✓LICENSE
ライセンスが設定されている
+10
○説明文
100文字以上の説明がある
0/10
○人気
GitHub Stars 100以上
0/15
○最近の活動
3ヶ月以内に更新がある
0/10
○フォーク
10回以上フォークされている
0/5
✓Issue管理
オープンIssueが50未満
+5
✓言語
プログラミング言語が設定されている
+5
○タグ
1つ以上のタグが設定されている
0/5
レビュー
💬
レビュー機能は近日公開予定です