Python FastAPI Development Best Practices
This skill provides comprehensive guidance for building production-grade FastAPI applications using Python 3.12 and modern development practices.
Technology Stack
You will work with the following technology stack:
**Python Version**: 3.12**Web Framework**: FastAPI**Data Validation**: Pydantic**ORM**: SQLAlchemy**Dependency Management**: Poetry**Database Migrations**: Alembic**User Management**: fastapi-users**Authentication**: fastapi-jwt-auth**Email**: fastapi-mail**Caching**: fastapi-cache**Rate Limiting**: fastapi-limiter**Pagination**: fastapi-paginationCore Development Principles
Follow these best practices when writing code:
1. Naming Conventions
Use descriptive, meaningful names for variables, functions, and classesNames should clearly communicate purpose and intentAvoid single-letter variables except in short loops or comprehensions2. Code Style (PEP 8)
Strictly adhere to PEP 8 style guideUse 4 spaces for indentationLimit lines to 88-100 characters (Black formatter standard)Use snake_case for functions and variables, PascalCase for classes3. Documentation
Write comprehensive docstrings for all functions and classesUse Google or NumPy docstring formatInclude parameter types, return types, and usage examplesDocument exceptions that may be raised4. Code Simplicity
Write simple, clear code that is easy to understandAvoid unnecessary complexity and over-engineeringPrefer explicit over implicit codeBreak complex functions into smaller, focused functions5. Pythonic Code
Use list comprehensions for creating lists when it improves readabilityLeverage dict comprehensions and generator expressions appropriatelyUse context managers (`with` statements) for resource managementUtilize built-in functions and standard library features6. Error Handling
Use try-except blocks to handle exceptions gracefullyCatch specific exceptions, not bare `except` clausesProvide meaningful error messagesLog errors appropriately for debuggingUse FastAPI's HTTPException for API error responses7. Environment Management
Always use virtual environments to isolate dependenciesUse Poetry for dependency management and virtual environment creationKeep `pyproject.toml` and `poetry.lock` up to dateDocument environment setup in README8. Testing
Write unit tests for all business logicUse pytest as the testing frameworkAim for high test coverage (80%+)Test edge cases and error conditionsUse fixtures for test data setup9. Type Safety
Use type hints for all function parameters and return valuesLeverage Pydantic models for data validationUse mypy for static type checkingDefine custom types when needed for clarity10. Global State
Avoid global variables to reduce side effectsUse dependency injection (FastAPI's `Depends`)Store configuration in environment variablesUse Pydantic's BaseSettings for configuration managementFastAPI-Specific Guidelines
Route Definition
Organize routes using APIRouterUse path operation decorators with proper HTTP methodsDefine response models using PydanticInclude status codes and response descriptionsDependency Injection
Use FastAPI's dependency injection systemCreate reusable dependencies for database sessions, authentication, etc.Leverage sub-dependencies for complex scenariosAuthentication & Authorization
Implement JWT-based authentication using fastapi-jwt-authUse fastapi-users for complete user managementProtect routes with proper authentication dependenciesImplement role-based access control where neededDatabase Operations
Use SQLAlchemy for database interactionsDefine models with proper relationships and constraintsUse Alembic for database migrationsImplement async database operations when possiblePerformance
Implement caching using fastapi-cache for expensive operationsUse fastapi-limiter to prevent abuseImplement pagination using fastapi-pagination for large datasetsUse async/await for I/O-bound operationsEmail Integration
Configure fastapi-mail for transactional emailsUse templates for email contentHandle email failures gracefullyProject Structure
Organize your FastAPI project with a clear structure:
```
project/
├── app/
│ ├── api/
│ │ ├── routes/
│ │ └── dependencies.py
│ ├── core/
│ │ ├── config.py
│ │ └── security.py
│ ├── models/
│ ├── schemas/
│ ├── services/
│ └── main.py
├── alembic/
├── tests/
├── pyproject.toml
└── README.md
```
Implementation Steps
When working on a FastAPI project:
1. **Setup**: Initialize Poetry, create virtual environment, install dependencies
2. **Configuration**: Set up environment variables and configuration management
3. **Database**: Define SQLAlchemy models and create initial Alembic migration
4. **Schemas**: Create Pydantic models for request/response validation
5. **Routes**: Implement API routes with proper dependencies and documentation
6. **Services**: Extract business logic into service layer
7. **Authentication**: Implement user authentication and authorization
8. **Testing**: Write comprehensive tests for all endpoints and services
9. **Documentation**: Ensure OpenAPI docs are complete and accurate
10. **Deployment**: Prepare production configuration and deployment scripts
Quality Checklist
Before considering code complete, verify:
[ ] All functions have type hints and docstrings[ ] Code follows PEP 8 style guide[ ] Unit tests exist and pass[ ] Error handling is implemented properly[ ] Dependencies are injected, not hardcoded[ ] Database queries are optimized[ ] Authentication is secure[ ] API documentation is complete[ ] Configuration uses environment variables[ ] No sensitive data in code or logsBy following these guidelines, you will create maintainable, scalable, and production-ready FastAPI applications.