Python FastAPI Best Practices
Expert guidance for building production-ready FastAPI applications with Python 3.12, following industry best practices and modern development patterns.
Technology Stack
You are working 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
1. Use Meaningful Names
Choose descriptive variable, function, and class names that clearly indicate their purposeAvoid single-letter variables except in list comprehensions or mathematical contextsUse snake_case for functions and variables, PascalCase for classes2. Follow PEP 8
Adhere to Python Enhancement Proposal 8 style guide for all code formattingUse 4 spaces for indentation (never tabs)Limit lines to 88 characters (Black formatter standard) or 79 characters (strict PEP 8)Use blank lines to separate logical sections3. Use Docstrings
Document all public functions, classes, and modules with docstringsUse Google-style or NumPy-style docstring format for consistencyInclude parameter descriptions, return types, and example usage where appropriate4. Keep It Simple
Write simple and clear code; avoid unnecessary complexityFollow the KISS principle (Keep It Simple, Stupid)Prefer readability over clevernessBreak complex functions into smaller, focused functions5. Use List Comprehensions
Prefer list comprehensions for creating lists over traditional for loops when appropriateKeep comprehensions readable; if they become too complex, use regular loopsExample: `squares = [x**2 for x in range(10)]` instead of manual loop construction6. Handle Exceptions
Use try-except blocks to handle exceptions gracefullyCatch specific exceptions rather than bare except clausesProvide meaningful error messagesUse FastAPI's HTTPException for API error responsesLog exceptions appropriately for debugging7. Use Virtual Environments
Always isolate project dependencies using virtual environmentsUse Poetry for dependency management and virtual environment creationNever install packages globally for project-specific dependencies8. Write Tests
Implement unit tests for all business logicUse pytest as the testing frameworkAim for high test coverage (80%+ for critical paths)Write integration tests for API endpointsUse test fixtures for reusable test data9. Use Type Hints
Utilize type hints for all function parameters and return valuesUse Pydantic models for request/response validationEnable static type checking with mypyType hints improve IDE autocomplete and catch errors early10. Avoid Global Variables
Limit the use of global variables to reduce side effectsUse dependency injection (FastAPI's Depends) insteadStore configuration in environment variables or settings objectsPass dependencies explicitly rather than relying on global stateFastAPI-Specific Guidelines
Route Handlers
Use appropriate HTTP methods (GET, POST, PUT, DELETE, PATCH)Define clear response models with PydanticUse status codes appropriately (200, 201, 404, 422, etc.)Implement proper error handling with HTTPExceptionDependency Injection
Leverage FastAPI's dependency injection systemUse Depends() for database sessions, authentication, and shared logicCreate reusable dependencies for common operationsDatabase Operations
Use SQLAlchemy ORM for database interactionsImplement database migrations with AlembicAlways use connection poolingClose database sessions properly using dependency injectionSecurity
Implement authentication using fastapi-jwt-authUse fastapi-users for comprehensive user managementApply rate limiting with fastapi-limiter to prevent abuseValidate all input data with Pydantic modelsNever store sensitive data in plain textPerformance
Implement caching with fastapi-cache for frequently accessed dataUse async/await for I/O-bound operationsImplement pagination with fastapi-pagination for large datasetsOptimize database queries to avoid N+1 problemsCode Organization
Structure your FastAPI project with clear separation of concerns:
```
project/
├── app/
│ ├── api/ # API routes
│ ├── core/ # Configuration, security
│ ├── models/ # SQLAlchemy models
│ ├── schemas/ # Pydantic schemas
│ ├── services/ # Business logic
│ └── dependencies/ # Dependency injection
├── tests/ # Test files
├── alembic/ # Database migrations
└── pyproject.toml # Poetry configuration
```
Example Implementation
When creating a new API endpoint:
1. Define the Pydantic schema for request/response
2. Create the SQLAlchemy model if needed
3. Implement the business logic in a service
4. Create the route handler with proper type hints
5. Add appropriate error handling
6. Write unit tests for the service
7. Write integration tests for the endpoint
Always prioritize code quality, maintainability, and security in your implementations.