When working with a large FastAPI project, organizing your code into packages and using a modular file structure helps in maintaining scalability, readability, and ease of collaboration.
package structure for a large FastAPI project:
1. Directory Structure my_fastapi_project/ β βββ app/ β βββ __init__.py β βββ main.py # Main FastAPI application β βββ models/ # Pydantic and ORM models β β βββ __init__.py β β βββ movie.py # Movie model definition β βββ api/ # API endpoints β β βββ __init__.py β β βββ v1/ # Versioned API (v1) β β β βββ __init__.py β β β βββ movies.py # Endpoints for movies β βββ core/ # Core settings, config, database connection, etc. β β βββ __init__.py β β βββ config.py # Settings configuration β βββ services/ # Business logic and services β β βββ __init__.py β β βββ movie_service.py # Logic for movie-related actions β βββ db/ # Database-related files β βββ __init__.py β βββ database.py # DB connection setup βββ tests/ # Test files β βββ __init__.py β βββ test_movies.py # Test cases for movies API βββ .env # Environment variables βββ requirements.txt # Python dependencies βββ README.md # Project documentation 2. Explanation of Directories and Files app/main.py: The entry point for your FastAPI application. This file initializes the app and includes middleware, routers, and other configurations. app/models/: Contains Pydantic models and ORM models (if youβre using a database like SQLAlchemy or Tortoise ORM). movie.py defines the Movie model, which might be a Pydantic schema or an ORM model. app/api/: Contains all the API routes organized by version (e.g., v1, v2). Inside each version, the routes are further organized by feature or resource. movies.py handles all the endpoints related to movies in version 1 of the API (e.g., /v1/movies/). app/core/: Contains application-wide settings, configurations, constants, and utilities. config.py manages application configurations like environment variables, API settings, etc. app/services/: Contains business logic and services related to different features of the application. movie_service.py might contain functions that handle complex business logic, such as interacting with the database, performing calculations, or managing caching, related to movies. app/db/: Handles database-related configurations and connection management. database.py manages the database connection setup, ORM initialization, and session handling. tests/: Contains unit and integration tests for your API, models, and services. test_movies.py contains test cases to ensure the correct functioning of movie-related API endpoints.