Python FastAPI
Category: backend October 19, 2025
Agent instructions for FastAPI backend development with Python
pythonfastapibackendapi
# FastAPI Development
## Setup Commands
- Create virtual environment: `python -m venv venv`
- Activate: `source venv/bin/activate` (Linux/Mac) or `venv\Scripts\activate` (Windows)
- Install dependencies: `pip install -r requirements.txt`
- Run dev server: `uvicorn main:app --reload`
- Run tests: `pytest`
## Code Style
- Follow PEP 8 style guide
- Use type hints for all function signatures
- Use Pydantic models for request/response validation
- Organize routes in separate router modules
- Keep business logic separate from route handlers
## Project Structure
app/ ├── main.py # FastAPI app initialization ├── routers/ # API route modules ├── models/ # Pydantic models ├── services/ # Business logic ├── db/ # Database connection & models └── tests/ # Test files
## Routing Best Practices
- Use APIRouter for modular route organization
- Include routers in main.py with appropriate prefixes and tags
- Use dependency injection for shared logic (auth, db sessions)
- Define response models explicitly for type safety
## Database Operations
- Use SQLAlchemy or Tortoise ORM for database operations
- Always use async database drivers when possible
- Implement database session dependency for automatic cleanup
- Use Alembic for database migrations
## Testing Instructions
- Write tests with pytest and pytest-asyncio
- Use TestClient for API endpoint testing
- Mock external dependencies
- Aim for > 80% code coverage
- Run `pytest --cov=app` to check coverage
## Common Patterns
- Use `Depends()` for dependency injection
- Use `BackgroundTasks` for non-blocking operations
- Implement proper error handling with HTTPException
- Use middleware for cross-cutting concerns (logging, CORS)
## Security Considerations
- Never commit `.env` files with secrets
- Use OAuth2 with password flow or JWT for authentication
- Validate all user inputs with Pydantic
- Implement rate limiting for public endpoints
- Use HTTPS in production
## PR Instructions
- Run `black .` to format code
- Run `flake8` for linting
- Ensure all tests pass: `pytest`
- Update API documentation if endpoints changed
- Check that OpenAPI docs are up to date at `/docs`