Learn FastAPI Β· 11/14

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:

python
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:

python
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 /me become /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:

python
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:

python
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:

nix
.
β”œβ”€β”€ 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 tests

Breakdown of the Structure:

  • src/: Contains the main application code.
  • main.py: The entry point of your application where you create the FastAPI instance 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 your APIRouter modules.
  • 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:

shell
pip install pydantic-settings

Now, let's create our settings file.

core/config.py:

python
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:

elixir
DATABASE_URL=postgresql://user:password@host:port/db
SECRET_KEY=your_super_secret_key

Now, whenever you need to access a setting, you can import the settings object.

Using Settings in Your App:

python
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:

python
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 πŸ“š

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:

  1. Configuration Management: Create a Settings class that inherits from pydantic_settings.BaseSettings. This class will manage the application's configuration. It should be placed in a section commented as core/config.py.

    • Define two configuration variables: APP_NAME: str and DATABASE_URL: str.
  2. 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 an APIRouter. Move the two user-related path operations (read_users and read_user_me) to this router. When you include this router in the main app, you must give it a URL prefix of /users and the tag "Users".
    • Item Router: In a section commented as routers/items.py, create another APIRouter. 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 /items and the tag "Items".
  3. Application Lifespan: Implement a lifespan asynchronous 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.").
  4. 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 Settings class.
    • Create the main FastAPI application instance. Use the APP_NAME from your settings as the application title and connect your lifespan manager.
    • Import and include both the user and item routers with their specified prefix and tags.

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:

  1. # --- In core/config.py ---

    • Must contain a Settings class that inherits from pydantic_settings.BaseSettings.
    • This class must define APP_NAME: str and DATABASE_URL: str.
  2. # --- In routers/users.py ---

    • Must define an APIRouter instance.
    • Must contain the path operations for read_users (at route /) and read_user_me (at route /me).
  3. # --- In routers/items.py ---

    • Must define an APIRouter instance.
    • Must contain the path operation for read_item (at route /{item_id}).
  4. # --- In main.py ---

    • Must define an asynccontextmanager named lifespan that prints the required startup and shutdown messages.
    • Must create an instance of the Settings class.
    • Must create the main FastAPI instance, configuring it with the title from settings and the lifespan manager.
    • Must include_router for the user router with prefix="/users" and tags=["Users"].
    • Must include_router for the item router with prefix="/items" and tags=["Items"].
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.