- Published on
How to Structure FastAPI Projects for Scalability in 2026
A scalable FastAPI project structure separates your code into logical folders like /app/api, /app/models, and /app/core to prevent a single file from becoming unmanageable. By using APIRouter (a tool to split your API into multiple files), you can organize your backend into modular pieces that are easy to test and maintain. This professional setup typically takes less than 10 minutes to configure but saves hundreds of hours as your application grows.
What should you have ready before starting?
To follow this guide, you will need a few basic tools installed on your computer. We recommend using Python 3.12 or higher to ensure compatibility with the latest asynchronous (code that can run multiple tasks at once) features.
- Python 3.12+: The programming language used for FastAPI.
- A Code Editor: VS Code or Cursor are excellent choices for beginners.
- Terminal Access: You will need to run commands in your Command Prompt, Terminal, or PowerShell.
You should also have a basic understanding of how to create a folder and save a text file. Don't worry if you haven't built a full API (Application Programming Interface) yet; we will walk through the logic together.
Why should you move beyond a single main.py file?
When you first learn FastAPI, most tutorials show you how to put everything into one main.py file. This is great for learning the basics because you can see all your code in one place. However, as you add more features like user accounts, payment processing, and database connections, that single file will eventually grow to thousands of lines.
Finding a specific bug in a 2,000-line file is frustrating and time-consuming. It also makes it difficult for multiple people to work on the project at the same time without breaking each other's code. By splitting your project into smaller pieces, you make the code "modular," meaning you can change one part without worrying about the rest.
We have found that organizing your project early prevents "technical debt" (the cost of fixing messy code later). A clean structure allows you to focus on building features rather than searching for where a specific function is hidden. It also makes your project look professional to potential employers or collaborators.
What does a professional FastAPI folder structure look like?
A production-ready project follows a specific hierarchy that keeps different types of code separate. You start with a root folder for your project, and inside that, you create an app folder to hold your actual Python code. This keeps your configuration files, like your list of dependencies, separate from your logic.
Inside the app folder, you should create several sub-folders to categorize your files. You will need an api folder for your endpoints (the URLs users visit), a core folder for settings, and a models folder for your data shapes. Each of these folders must contain an __init__.py file (an empty file that tells Python to treat the folder as a package).
Here is a visual representation of how your folders should look:
my_fastapi_project/
├── app/
│ ├── __init__.py
│ ├── main.py # The entry point that starts the app
│ ├── api/ # Folders for your URL routes
│ │ ├── __init__.py
│ │ └── v1/ # Versioning your API
│ │ ├── __init__.py
│ │ └── endpoints/
│ ├── core/ # Global settings and security
│ │ ├── __init__.py
│ │ └── config.py
│ ├── models/ # Database structures
│ │ ├── __init__.py
│ │ └── user.py
│ └── schemas/ # Data validation rules
│ ├── __init__.py
│ └── user.py
├── requirements.txt # List of needed libraries
└── .env # Secret keys and sensitive data
How do you set up the Core configuration?
The core folder is the brain of your application where you store settings that every other part of the app might need. Instead of typing your database password or API keys directly into your code, you store them in a .env file and read them through a config file. This is a security best practice because it keeps your secrets out of your code history.
Create a file named app/core/config.py and add the following code. This uses Pydantic (a library for data validation) to ensure your settings are correct.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# The name of your project
PROJECT_NAME: str = "My Scalable API"
# The version of your software
VERSION: str = "1.0.0"
# A secret key for security (keep this private!)
SECRET_KEY: str = "super-secret-key-123"
class Config:
# Tells Python to look for a .env file
env_file = ".env"
# Create one instance of settings to use everywhere
settings = Settings()
How do you use APIRouter to split your routes?
The APIRouter is one of the most powerful features in FastAPI for staying organized. It allows you to define "mini-apps" for different sections of your site, like /users or /products, in their own files. Later, you "include" these routers back into your main application file.
Create a file at app/api/v1/endpoints/users.py. This file will only handle user-related tasks, which keeps your code clean and focused.
from fastapi import APIRouter
# Create the router for user-related paths
router = APIRouter()
@router.get("/")
def get_users():
# This function runs when someone visits /users/
return [{"username": "alex"}, {"username": "sam"}]
@router.post("/create")
def create_user(name: str):
# This function runs when someone sends data to /users/create
return {"message": f"User {name} created successfully"}
How do you tie everything together in main.py?
Now that you have your settings and your first router, you need to tell FastAPI where to find them. Your app/main.py file acts as the conductor of the orchestra, bringing all the pieces together. Instead of containing logic, this file mostly contains "imports" (bringing in code from other files).
Open your app/main.py file and set it up like this:
from fastapi import FastAPI
from app.api.v1.endpoints import users
from app.core.config import settings
# Initialize the FastAPI app using our settings
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION
)
# Include the user router
# prefix="/users" means all routes in that file start with /users
# tags=["users"] helps organize the automatic documentation
app.include_router(users.router, prefix="/users", tags=["users"])
@app.get("/")
def root():
return {"message": "Welcome to the Scalable API!"}
How do you verify the setup is working?
Once your files are in place, it is time to run the server and see if your structure works. You will use a tool called Uvicorn (a lightning-fast server implementation for Python) to launch your application. Open your terminal in the root my_fastapi_project folder.
Run the following command:
uvicorn app.main:app --reload
After running the command, you should see a message saying "Application startup complete." Open your web browser and go to http://127.0.0.1:8000/docs. You should see a beautifully organized documentation page showing your /users endpoints separately from your root endpoint.
What are common mistakes beginners make?
One frequent error is forgetting to add the __init__.py files in new folders. Without these files, Python might not realize that the folder contains code it is allowed to import. If you get an "ImportError," check to make sure every folder in your app directory has that empty file.
Another mistake is using "circular imports," which happens when File A tries to import File B, while File B is also trying to import File A. This creates a loop that crashes your program. To avoid this, always try to import from the core or models folders rather than having two API files import from each other.
Finally, don't worry if the folder structure feels "too big" for a small project. It is normal to feel like you are creating too many files at the start. It is much easier to start with a good structure than to try and reorganize a messy project once it becomes popular.
What should you learn next?
Now that you have a solid foundation, you can begin adding more advanced features to your project. You might want to explore how to connect a database using SQLAlchemy (a tool to talk to databases using Python code). You could also look into Claude Sonnet 4 to help you generate Pydantic schemas (rules for what your data should look like) based on your project needs.
As you build, remember to keep your functions small and focused on one task. This makes your code easier to test and more reliable for your users.
For detailed guides, visit the official FastAPI documentation.