Structuring FastAPI Projects: Essential File Organization

Laamiri Ouail
4 min readJul 26, 2024

--

Introduction

In the world of modern web development, FastAPI has emerged as a powerful and efficient framework for building APIs with Python. Its speed, simplicity, and automatic documentation features have made it a favorite among developers. However, as with any project, proper organization is key to maintaining scalability and readability. This article will dive into the essential file structures for FastAPI projects.

Whether you’re new to FastAPI or looking to optimize your existing projects, understanding these foundational elements will set you on the path to creating well-structured, maintainable APIs. We’ll cover the recommended directory layout, core files you’ll need, and best practices for organizing your code. By the end of this article, you’ll have a clear blueprint for structuring your FastAPI projects .

Essential File Structure for FastAPI Projects

In the world of FastAPI development, a well-organized project structure is the foundation of maintainable and scalable code. Let’s dive into a robust file structure that balances clarity, modularity, and best practices:

Root Directory:

At the heart of our project, we find several key elements:

  • docs/: This folder houses project documentation, ensuring that your API is well-documented and easy for others to understand and use.
  • README.md: The face of your project on platforms like GitHub, providing a quick overview and essential information for users and contributors.
  • requirements/: Instead of a single requirements file, this structure separates dependencies:
    - dev.txt: Lists packages needed for development, such as testing and linting tools.
    - prod.txt: Contains only the essential packages required for production deployment.
    - test.txt: Contains only the essential packages required for the test.
  • server.py: The entry point of your application, where the FastAPI instance is typically created and configured.

src/ Directory:

The src/ folder is where the magic happens. This structure keeps your code organized and modular:

  • auth/: Houses authentication-related code, crucial for securing your API.
  • base/: Contains base classes and core functionality that other parts of the application build upon.
  • config/: This directory contains configuration settings. It uses Pydantic settings to manage configurations from .env files, ensuring that environment-specific settings are correctly loaded and validated.
  • controllers/: Manages the flow of data between the model and the view in your application.
  • database/: Includes database configurations, connection management, and potentially migration scripts.
  • enums/: Stores enumeration classes, providing a clean way to define constants and choices.
  • env/: Manages environment-specific configurations, allowing your app to behave differently in development and production.
  • middlewares/: Contains custom middleware for request/response processing.
  • models/: Defines your data models, typically corresponding to database tables.
  • public/: Stores static files like images or CSS, if your API serves any static content.
  • schemas/: Defines Pydantic models for request/response data validation and serialization.
  • services/: Houses business logic, keeping it separate from your route handlers.
  • shared/: Contains code and utilities shared across different parts of your application.
  • utils/: A home for utility functions and helper classes used throughout your project.

This structure embodies several key principles:
1. Separation of Concerns: Each directory has a specific purpose, making it easy to locate and maintain different aspects of your application.

2. Scalability: As your project grows, this structure provides clear places for new components without cluttering your main directory.

3. Modularity: The breakdown into specific directories (like ‘auth’, ‘models’, ‘schemas’) promotes modular development, making it easier to test and refactor individual components.

4. Developer-Friendly: With a clear structure, new team members can quickly understand the project layout and start contributing effectively.

By adopting this file structure, you’re setting yourself up for success in your FastAPI journey. It provides a solid foundation that can adapt to the growing complexity of your project while maintaining clarity and organization.

Streamlining Your Project Setup

To help you quickly implement this file structure, I’ve created a simple shell script that automates the process. This script will create all the necessary directories and files in your project folder, saving you time and ensuring consistency.

Here’s how to use it:

  1. Copy the following script and save it as setup_fastapi_project.sh in your desired project location.
  2. Make the script executable by running chmod +x setup_fastapi_project.sh in your terminal.
  3. Execute the script by running ./setup_fastapi_project.sh project-name .
#!/bin/bash

# Check if a project name is provided
if [ -z "$1" ]; then
echo "Error: No project name provided."
echo "Usage: $0 <project_name>"
exit 1
fi

# Set the project name from the first argument
PROJECT_NAME=$1

# Create the main project directory
mkdir -p "$PROJECT_NAME"

# Navigate into the project directory
cd "$PROJECT_NAME" || exit

# Create the Dockerfile
touch Dockerfile
touch .dockerignore

# Create the .gitignore file
touch .gitignore

# Create the requirements directory and files
mkdir -p requirements
touch requirements/dev.txt
touch requirements/prod.txt
touch requirements/test.txt

# Create the server.py file
touch server.py

# Create the src directory structure
mkdir -p src/auth
touch src/auth/__init__.py
mkdir -p src/controller
touch src/controller/__init__.py
mkdir -p src/config
touch src/config/__init__.py
mkdir -p src/database
touch src/database/__init__.py
mkdir -p src/env
touch src/__init__.py
touch src/env/__init__.py
mkdir -p src/models
touch src/models/__init__.py
mkdir -p src/schemas
touch src/schemas/__init__.py
mkdir -p src/service
touch src/service/__init__.py
mkdir -p src/utils
touch src/utils/__init__.py
mkdir -p src/shared
touch src/shared/__init__.py


echo "Directory structure for project '$PROJECT_NAME' created successfully."

Remember, while the structure we’ve outlined provides an excellent starting point, don’t be afraid to adapt it to your specific needs. The goal is to create an organization that works for you and your team, facilitating efficient development and easy maintenance.

As you embark on your FastAPI journey, keep this structure in mind. Use the provided script to quickly set up new projects, and focus your energy on what really matters — building powerful, efficient APIs that solve real-world problems.

With a solid foundation in place, you’re now ready to harness the full potential of FastAPI. Happy coding, and may your APIs be fast, robust, and a joy to develop!

--

--