When structuring a folder for a Python FastAPI project, it’s essential to maintain modularity and scalability, especially as your project grows. A good folder structure helps to separate concerns, making it easier to manage and maintain the codebase.
Here’s a recommended folder structure for a typical FastAPI project:
Recommended Folder Structure
my_fastapi_project/
│
├── app/ # Main application code
│ ├── __init__.py
│ ├── main.py # Entry point for the FastAPI application
│ ├── api/ # API routes and business logic
│ │ ├── __init__.py
│ │ ├── v1/ # Versioned API (optional, but good for future scalability)
│ │ │ ├── __init__.py
│ │ │ ├── endpoints/ # Routes for version 1 API
│ │ │ │ ├── __init__.py
│ │ │ │ ├── user.py # Example: user-related routes
│ │ │ │ ├── item.py # Example: item-related routes
│ │ ├── v2/ # (Optional) Future version of the API
│ │ ├── dependencies.py # Shared dependencies (e.g., DB session)
│ ├── core/ # Core components like settings, config, security
│ │ ├── __init__.py
│ │ ├── config.py # Configuration settings (e.g., environment variables)
│ │ ├── security.py # Security-related utilities (e.g., JWT)
│ │ ├── settings.py # Settings management (e.g., loading env variables)
│ ├── models/ # ORM models or Pydantic schemas
│ │ ├── __init__.py
│ │ ├── user.py # Example: user model
│ │ ├── item.py # Example: item model
│ ├── schemas/ # Pydantic schemas for validation
│ │ ├── __init__.py
│ │ ├── user.py # Example: user schema
│ │ ├── item.py # Example: item schema
│ ├── services/ # Business logic and service layer
│ │ ├── __init__.py
│ │ ├── user_service.py # Example: user service
│ │ ├── item_service.py # Example: item service
│ ├── db/ # Database-related code (e.g., SQLAlchemy models, migrations)
│ │ ├── __init__.py
│ │ ├── session.py # Database session management
│ │ ├── init_db.py # Database initialization code (e.g., creating tables)
│ ├── tests/ # Unit and integration tests
│ │ ├── __init__.py
│ │ ├── test_user.py # Example test file for user-related functionality
│ │ ├── test_item.py # Example test file for item-related functionality
│ ├── utils/ # Utility functions that are used across the app
│ │ ├── __init__.py
│ │ ├── date_utils.py # Example utility: date-related functions
│
├── .env # Environment variables for sensitive data (e.g., DB URI, API keys)
├── .gitignore # Git ignore file to exclude unnecessary files
├── requirements.txt # Project dependencies (including FastAPI and Uvicorn)
├── alembic.ini # Alembic configuration file (if using migrations with SQLAlchemy)
├── Dockerfile # Dockerfile for containerizing the app (optional)
├── docker-compose.yml # Docker Compose file for multi-container setup (optional)
└── README.md # Project documentation
Explanation of the Structure:
app/
: This is where the majority of your code resides. It contains all your app-specific logic and modules.