Organizing your FastAPI project files helps keep your code clean and easy to find. It makes working on your app simpler and faster.
0
0
Folder structure patterns in FastAPI
Introduction
When starting a new FastAPI project to keep code neat.
When your app grows and you add more features or routes.
When working with a team to avoid confusion about file locations.
When you want to separate different parts like models, routes, and services.
When preparing your app for easier testing and maintenance.
Syntax
FastAPI
project_root/ ├── app/ │ ├── main.py │ ├── models.py │ ├── routes/ │ │ ├── __init__.py │ │ ├── users.py │ │ └── items.py │ ├── services/ │ │ ├── __init__.py │ │ └── user_service.py │ └── database.py ├── tests/ │ ├── test_users.py │ └── test_items.py └── requirements.txt
The app/ folder holds your main application code.
Subfolders like routes/ and services/ separate different parts of your app.
Examples
A simple structure with main app file, models, and routes separated.
FastAPI
app/ ├── main.py ├── models.py ├── routes/ │ ├── users.py │ └── items.py
More detailed structure splitting models into their own folder and adding services.
FastAPI
app/ ├── main.py ├── models/ │ ├── user.py │ └── item.py ├── routes/ │ ├── users.py │ └── items.py ├── services/ │ └── auth.py
A scalable pattern with versioned API, core utilities, database, and models separated.
FastAPI
project_root/ ├── app/ │ ├── __init__.py │ ├── main.py │ ├── api/ │ │ ├── v1/ │ │ │ ├── __init__.py │ │ │ ├── users.py │ │ │ └── items.py │ ├── core/ │ │ ├── config.py │ │ └── security.py │ ├── db/ │ │ ├── base.py │ │ └── session.py │ └── models/ │ ├── user.py │ └── item.py
Sample Program
This is a simple FastAPI app with a root route. The folder structure comment shows how files are organized.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get('/') async def read_root(): return {"message": "Welcome to the FastAPI app!"} # Folder structure: # project_root/ # ├── app/ # │ ├── main.py (this file) # │ ├── routes/ # │ │ └── users.py # │ ├── models.py # │ └── database.py # └── requirements.txt
OutputSuccess
Important Notes
Keep your folder names clear and consistent.
Use __init__.py files to make folders Python packages when needed.
As your app grows, consider splitting code by features or layers (models, routes, services).
Summary
Good folder structure keeps your FastAPI project organized and easy to maintain.
Separate code by purpose: routes, models, services, and database.
Start simple and adjust structure as your app grows.