Structuring Large Applications
7 min read
Structuring Large FastAPI Applications ποΈ
As your FastAPI application grows from a simple proof-of-concept to a full-fledged production service, keeping all your code in a single main.py file becomes the digital equivalent of stuffing everything into one giant drawer. It might work for a while, but soon you'll be spending more time untangling things than actually building.
This guide will walk you through the industry-standard practices for organizing your FastAPI projects, making them scalable, maintainable, and a joy to work on.
1. Using APIRouter to Split the App into Modules
The Problem: Your main.py is becoming a behemoth. It has endpoints for users, items, orders, and that weird experimental feature for tracking rubber duck migrations. It's hard to find anything, and a small change in one area could accidentally break something completely unrelated. π¦
The Solution: APIRouter
Think of APIRouter as a "mini-FastAPI" application. It allows you to group related endpoints into separate files, keeping your codebase clean and organized. This is similar to "Blueprints" in Flask.
How it Works
You create an instance of APIRouter and define your path operations on it, just like you would with a FastAPI instance. Then, you "include" this router in your main application.
Example: A Simple User Router
Let's create a router for user-related endpoints.
routers/users.py:
from fastapi import APIRouter
router = APIRouter()
@router.get("/users/", tags=["users"])
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]
@router.get("/users/me", tags=["users"])
async def read_user_me():
return {"username": "current_user"}Now, let's include this router in our main application.
main.py:
from fastapi import FastAPI
from .routers import users
app = FastAPI()
app.include_router(users.router)It's that simple! Now, all the routes defined in users.router are part of your main application.
A Funny Exaggeration: Imagine your application is a massive concert. Without APIRouter, your main.py is the lone stage manager trying to coordinate every single musician, roadie, and food vendor. With APIRouter, you have dedicated managers for each section: one for the rock band (user routes), one for the orchestra (item routes), and one for the hot dog stands (order routes). Much more manageable! π
APIRouter Power-Ups πͺ
APIRouter comes with some handy parameters to reduce code duplication:
prefix: Adds a prefix to all routes in the router. For example,prefix="/users"will make the routes/and/mebecome/users/and/users/me.tags: Assigns a tag to all routes, which is great for organizing your API documentation.dependencies: Applies dependencies to all routes in the router, perfect for things like authentication.
Example with Power-Ups:
routers/items.py:
from fastapi import APIRouter, Depends
# A dummy dependency for demonstration
async def get_current_user():
return {"username": "admin"}
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_current_user)]
)
@router.get("/")
async def read_items():
return [{"name": "Item 1"}, {"name": "Item 2"}]main.py:
from fastapi import FastAPI
from .routers import users, items
app = FastAPI()
app.include_router(users.router)
app.include_router(items.router)Now, all routes in items.router will be prefixed with /items, have the "items" tag in the docs, and will require the get_current_user dependency.
2. Standard Project Directory Structures and Best Practices
The Problem: You've started splitting your code into multiple files, but now you have a new problem: where does everything go? What's a good way to organize your routers, models, and business logic? A consistent structure makes it easier for you and your team to navigate the codebase.
The Solution: A Scalable Directory Structure
While there are many ways to structure a project, a common and effective approach for larger applications is to organize by feature or domain.
Here's a widely-used project structure:
.
βββ alembic/ # Database migrations
βββ src/
β βββ __init__.py
β βββ main.py # Main FastAPI app
β βββ core/ # Core components like config and security
β β βββ __init__.py
β β βββ config.py
β β βββ security.py
β βββ db/ # Database session management
β β βββ __init__.py
β β βββ session.py
β βββ models/ # SQLAlchemy models
β β βββ __init__.py
β β βββ user.py
β βββ schemas/ # Pydantic schemas
β β βββ __init__.py
β β βββ user.py
β βββ services/ # Business logic
β β βββ __init__.py
β β βββ user_service.py
β βββ routers/ # API routers
β βββ __init__.py
β βββ users.py
βββ tests/ # Application testsBreakdown of the Structure:
src/: Contains the main application code.main.py: The entry point of your application where you create theFastAPIinstance and include your routers.core/: Holds application-wide configurations, security settings, etc.db/: Manages the database connection and session.models/: Defines your database models (e.g., SQLAlchemy models).schemas/: Contains your Pydantic models for data validation and serialization.services/: Houses the business logic, keeping it separate from your API routes.routers/: Contains yourAPIRoutermodules.tests/: Includes your unit and integration tests.
Interesting Fact: The __init__.py files are what make Python treat directories as "packages," allowing you to import modules from them.
3. Managing Configuration and Secrets with Pydantic BaseSettings
The Problem: You have database URLs, secret keys, and other configuration values scattered throughout your code. This is a security nightmare and makes it difficult to manage different environments (development, staging, production). The Twelve-Factor App methodology suggests storing configuration in the environment.
The Solution: Pydantic's BaseSettings
Pydantic provides a BaseSettings class that makes managing application settings a breeze. It can automatically read settings from environment variables and .env files, and it provides type validation.
How it Works
You create a class that inherits from BaseSettings and define your configuration attributes with type hints.
Example: Creating a Settings Class
First, you'll need to install pydantic-settings:
pip install pydantic-settingsNow, let's create our settings file.
core/config.py:
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
app_name: str = "My FastAPI App"
database_url: str
secret_key: str
model_config = SettingsConfigDict(env_file=".env")
settings = Settings()Create a .env file in your project's root directory:
.env:
DATABASE_URL=postgresql://user:password@host:port/db
SECRET_KEY=your_super_secret_keyNow, whenever you need to access a setting, you can import the settings object.
Using Settings in Your App:
from fastapi import FastAPI
from .core.config import settings
app = FastAPI(title=settings.app_name)
@app.get("/info")
async def info():
return {
"app_name": settings.app_name,
"database_url_is_set": settings.database_url is not None,
}Pydantic will automatically read the values from the .env file and validate their types. If a required setting is missing, it will raise an error on startup, which is much better than failing at runtime.
4. Lifespan Events: Managing Application Startup and Shutdown
The Problem: Your application needs to perform certain actions when it starts up, like establishing a database connection pool, and other actions when it shuts down, like closing those connections.
The Solution: Lifespan Events
FastAPI provides a lifespan argument that allows you to define code to be executed before the application starts and when it shuts down. This is the recommended way to manage resources that need to be initialized and cleaned up.
How it Works
You create an async context manager function and pass it to the FastAPI instance. The code before the yield statement is executed on startup, and the code after is executed on shutdown.
Example: Managing a Database Connection Pool
Let's imagine we're using a database library that requires explicit connection and disconnection.
main.py:
from contextlib import asynccontextmanager
from fastapi import FastAPI
# A dummy database client for demonstration
class DummyDBClient:
async def connect(self):
print("Connecting to the database...")
async def close(self):
print("Closing the database connection...")
db_client = DummyDBClient()
@asynccontextmanager
async def lifespan(app: FastAPI):
# Code to be executed on startup
await db_client.connect()
yield
# Code to be executed on shutdown
await db_client.close()
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def root():
return {"message": "Hello World"}When you run this application, you'll see "Connecting to the database..." printed to the console once at the beginning. When you stop the application (e.g., with Ctrl+C), you'll see "Closing the database connection...".
A Word of Caution: There is an older, now deprecated, way of handling startup and shutdown events using @app.on_event("startup") and @app.on_event("shutdown"). It's recommended to use the lifespan context manager for new applications.
Further Reading π
- FastAPI Documentation on Bigger Applications: https://fastapi.tiangolo.com/tutorial/bigger-applications/
- Pydantic Settings Management: https://docs.pydantic.dev/latest/usage/settings/
- FastAPI Lifespan Events: https://fastapi.tiangolo.com/advanced/events/
Challenge
You have been provided with a monolithic FastAPI application where all logic, configuration, and routes are in a single script. Your task is to refactor this code into a well-structured, scalable application using industry-standard practices.
Requirements:
Configuration Management: Create a
Settingsclass that inherits frompydantic_settings.BaseSettings. This class will manage the application's configuration. It should be placed in a section commented ascore/config.py.- Define two configuration variables:
APP_NAME: strandDATABASE_URL: str.
- Define two configuration variables:
Modular Routers: Separate the user and item endpoints into their own modules using
APIRouter.- User Router: In a section commented as
routers/users.py, create anAPIRouter. Move the two user-related path operations (read_usersandread_user_me) to this router. When you include this router in the main app, you must give it a URL prefix of/usersand the tag"Users". - Item Router: In a section commented as
routers/items.py, create anotherAPIRouter. Move the item-related path operation (read_item) to this router. When you include this router in the main app, it must have a URL prefix of/itemsand the tag"Items".
- User Router: In a section commented as
Application Lifespan: Implement a
lifespanasynchronous context manager in your main application file to handle startup and shutdown events.- On startup, it should
print("Connecting to the database..."). - On shutdown, it should
print("Disconnecting from the database.").
- On startup, it should
Main Application File: The main application logic should be in a section commented as
main.py. This file should be clean and act as the entry point.- Instantiate your
Settingsclass. - Create the main
FastAPIapplication instance. Use theAPP_NAMEfrom your settings as the applicationtitleand connect yourlifespanmanager. - Import and include both the user and item routers with their specified
prefixandtags.
- Instantiate your
Expected result
Your solution should be a single Python code block that contains the complete, refactored application.
The code must be organized into four distinct sections, delineated by comments, to simulate a proper project structure:
# --- In core/config.py ---- Must contain a
Settingsclass that inherits frompydantic_settings.BaseSettings. - This class must define
APP_NAME: strandDATABASE_URL: str.
- Must contain a
# --- In routers/users.py ---- Must define an
APIRouterinstance. - Must contain the path operations for
read_users(at route/) andread_user_me(at route/me).
- Must define an
# --- In routers/items.py ---- Must define an
APIRouterinstance. - Must contain the path operation for
read_item(at route/{item_id}).
- Must define an
# --- In main.py ---- Must define an
asynccontextmanagernamedlifespanthat prints the required startup and shutdown messages. - Must create an instance of the
Settingsclass. - Must create the main
FastAPIinstance, configuring it with thetitlefrom settings and thelifespanmanager. - Must
include_routerfor the user router withprefix="/users"andtags=["Users"]. - Must
include_routerfor the item router withprefix="/items"andtags=["Items"].
- Must define an