
fastapi
by mmbilal2725
SKILL.md
name: fastapi description: | Comprehensive FastAPI development skill for building production-ready Python APIs from Hello World to enterprise applications. Use this skill when the user asks about FastAPI or wants to build APIs with Python, including: (1) Creating new FastAPI projects or applications, (2) Building REST APIs with path operations, query parameters, request bodies, (3) Implementing authentication and authorization with OAuth2, JWT tokens, API keys, (4) Database integration with SQLModel, SQLAlchemy, CRUD operations, (5) Project structuring with APIRouter, dependencies, middleware, (6) Testing FastAPI applications with TestClient and pytest, (7) Deployment strategies including Docker, cloud platforms, HTTPS configuration, (8) Advanced features like WebSockets, background tasks, CORS, file uploads, (9) Debugging FastAPI issues or improving existing FastAPI code, (10) Questions about FastAPI best practices, patterns, or architecture. Triggers include phrases like "build an API", "create FastAPI app", "add authentication", "set up database", "deploy FastAPI", "test endpoints", "FastAPI tutorial", or any mention of REST API development in Python.
FastAPI Development Skill
This skill provides comprehensive guidance for building FastAPI applications from simple Hello World apps to production-ready enterprise APIs.
Quick Start Workflow
1. Hello World Application
For users asking to create their first FastAPI app:
# Copy from: assets/hello-world.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Run with: fastapi dev main.py
Access docs at: http://127.0.0.1:8000/docs
2. CRUD API Application
For users building an API with database operations:
- Use template from
assets/crud-api.py - Includes SQLModel setup, full CRUD operations, validation
- Covers path parameters, query parameters, request/response models
3. Authentication Application
For users needing authentication:
- Use template from
assets/auth-jwt.py - Includes JWT tokens, password hashing, OAuth2 flow
- Ready-to-use login endpoint and protected routes
Reference Documentation
The skill includes detailed reference files for different aspects of FastAPI development. Load these as needed:
Core Concepts
- references/basics.md - Path operations, query/path parameters, request body, response models, validation, form data, file uploads, error handling
- Use when: Starting new project, basic endpoint creation, data validation
Dependency Injection
- references/dependencies.md - Dependency injection system, classes as dependencies, sub-dependencies, yield dependencies, caching
- Use when: Sharing logic, database sessions, authentication, configuration
Security
- references/security.md - OAuth2, JWT tokens, password hashing, API keys, HTTP Basic Auth, CORS
- Use when: Adding authentication, authorization, securing endpoints, user management
Database
- references/databases.md - SQLModel, CRUD operations, relationships, queries, migrations with Alembic
- Use when: Database integration, models, CRUD endpoints, complex queries
Project Structure
- references/project-structure.md - APIRouter, bigger applications, file organization, API versioning
- Use when: Structuring larger apps, organizing code, modular design
Testing
- references/testing.md - TestClient, fixtures, dependency overrides, database testing, authentication testing
- Use when: Writing tests, test setup, mocking dependencies
Deployment
- references/deployment.md - Docker, production servers, HTTPS, environment variables, cloud deployment
- Use when: Deploying to production, Docker setup, HTTPS configuration
Advanced Features
- references/advanced.md - Background tasks, middleware, WebSockets, templates, custom responses, rate limiting
- Use when: Real-time features, background processing, custom functionality
Common Workflows
Workflow 1: New Project Setup
User asks: "Help me create a new FastAPI project"
Steps:
- Determine project complexity (Hello World, CRUD API, or Full Application)
- For simple: Use
assets/hello-world.py - For CRUD: Use
assets/crud-api.pyas template - For auth: Include
assets/auth-jwt.pypatterns - Create
requirements.txtfromassets/requirements.txt - Provide
.env.examplefrom assets for configuration
Installation:
pip install "fastapi[standard]"
# Add sqlmodel for database: pip install sqlmodel
# Add auth packages: pip install "python-jose[cryptography]" "passlib[bcrypt]"
Workflow 2: Adding Authentication
User asks: "Add authentication to my FastAPI app"
Steps:
- Read
references/security.mdfor OAuth2 + JWT implementation - Review
assets/auth-jwt.pyfor complete working example - Implement:
- Password hashing utilities
- Token creation/validation
- User authentication dependency
- Login endpoint
- Protected routes with
Depends(get_current_user)
- Configure SECRET_KEY in environment variables
Workflow 3: Database Integration
User asks: "Connect my FastAPI app to a database"
Steps:
- Read
references/databases.mdfor SQLModel setup - Review
assets/crud-api.pyfor complete example - Create models with inheritance (Base, DB, Public, Create, Update)
- Set up engine and session dependency
- Implement CRUD endpoints
- For production: Set up Alembic migrations
Workflow 4: Project Structuring
User asks: "How should I structure my FastAPI project?"
Steps:
- Read
references/project-structure.mdfor patterns - For small projects (<5 endpoints): Single file is fine
- For medium projects: Use routers for different resources
- For large projects: Implement full structure:
app/ ├── api/v1/endpoints/ # Route handlers ├── core/ # Config, security ├── models/ # Database models ├── schemas/ # Pydantic models ├── services/ # Business logic └── tests/ # Test files
Workflow 5: Testing Setup
User asks: "Help me write tests for my FastAPI app"
Steps:
- Read
references/testing.mdfor TestClient usage - Install:
pip install pytest httpx - Create
tests/conftest.pywith fixtures - Use in-memory SQLite for database tests
- Override dependencies for authentication
- Write tests for each endpoint (success and error cases)
- Run:
pytest --cov=app
Workflow 6: Production Deployment
User asks: "Deploy my FastAPI app to production"
Steps:
- Read
references/deployment.mdfor strategies - Create
Dockerfilefromassets/Dockerfile - Set up
docker-compose.ymlfromassets/docker-compose.yml - Configure environment variables (SECRET_KEY, DATABASE_URL)
- Set up HTTPS with nginx reverse proxy
- Configure Gunicorn with Uvicorn workers
- Implement health checks
- Set up monitoring and logging
Progressive Implementation Guide
Level 1: Hello World (Beginner)
- Single file application
- Basic GET endpoints
- Path and query parameters
- Run with
fastapi dev
Reference: references/basics.md - First sections
Level 2: CRUD API (Intermediate)
- SQLModel integration
- Full CRUD operations
- Request/response models
- Error handling
- Basic validation
Reference: references/basics.md + references/databases.md
Level 3: Production API (Advanced)
- Authentication with JWT
- Project structure with routers
- Comprehensive testing
- Database migrations
- Docker deployment
- HTTPS configuration
Reference: All reference files
Templates and Assets
Located in assets/ directory:
- hello-world.py - Minimal FastAPI application
- crud-api.py - Complete CRUD API with SQLModel
- auth-jwt.py - Authentication with JWT tokens
- requirements.txt - Dependencies template
- Dockerfile - Production Docker setup
- docker-compose.yml - Multi-service deployment
- .env.example - Environment variables template
Best Practices
Code Organization
- Use Pydantic models for validation
- Separate database models from API schemas
- Use dependency injection for reusable logic
- Organize routes with APIRouter for larger apps
- Keep business logic in service layer
Security
- Never commit SECRET_KEY or credentials
- Use environment variables for configuration
- Hash passwords with bcrypt
- Implement HTTPS in production
- Set appropriate CORS origins
- Use OAuth2 scopes for fine-grained permissions
Database
- Use SQLModel for type safety
- Implement separate models (Base, DB, Public, Create, Update)
- Use Alembic for migrations in production
- Configure connection pooling
- Add indexes to frequently queried fields
Testing
- Write tests for all endpoints
- Use in-memory database for tests
- Override dependencies for isolation
- Test both success and error cases
- Aim for high coverage (>80%)
Deployment
- Use Gunicorn with Uvicorn workers
- Set worker count:
(2 x num_cores) + 1 - Configure health checks
- Enable compression (GZip)
- Implement logging and monitoring
- Use Docker for consistency
- Configure HTTPS with Let's Encrypt
Troubleshooting Common Issues
Issue: "Module not found"
- Check virtual environment activation
- Verify dependencies installed:
pip install -r requirements.txt
Issue: "422 Validation Error"
- Check request body matches Pydantic model
- Verify field types and required fields
- Use
/docsto see expected schema
Issue: "401 Unauthorized"
- Verify token in Authorization header:
Bearer <token> - Check token expiration
- Confirm SECRET_KEY matches between creation and validation
Issue: Database connection errors
- Verify DATABASE_URL format
- Check database is running
- For SQLite: Ensure directory exists
- For PostgreSQL/MySQL: Test connection separately
Issue: CORS errors
- Add CORSMiddleware with appropriate origins
- Include credentials if needed
- Check allowed methods and headers
When NOT to Use This Skill
This skill focuses on FastAPI. For other frameworks:
- Django REST Framework - use different skill/approach
- Flask - use different skill/approach
- General Python questions - standard Python knowledge applies
Getting Help
If stuck or need more details:
- Check appropriate reference file for topic
- Review relevant asset template
- Consult FastAPI official docs at https://fastapi.tiangolo.com
- Check error messages in
/docsendpoint for validation issues
Score
Total Score
Based on repository quality metrics
SKILL.mdファイルが含まれている
ライセンスが設定されている
100文字以上の説明がある
GitHub Stars 100以上
3ヶ月以内に更新がある
10回以上フォークされている
オープンIssueが50未満
プログラミング言語が設定されている
1つ以上のタグが設定されている
Reviews
Reviews coming soon