Every FastAPI app starts as one tidy file, then a catalog, some settings and a few tests land in it, and scrolling becomes the main job.
Quick answer: a good FastAPI project structure for a small app is one app package with main.py plus routers, schemas, models and core folders, each holding an __init__.py, with tests beside it. Run it from the project root:
bookstore/
app/
main.py # creates the app, includes the routers
core/config.py # settings
routers/ # URL endpoints
schemas/ # Pydantic request and response shapes
models/ # your data
tests/
fastapi dev app/main.py
I built and ran this exact project on Python 3.12.5 and FastAPI 0.162.2. The running example is a small catalog API for a made-up Boston bookstore called Liberty Books, and I broke it on purpose to capture the real import errors.
When does one FastAPI file stop being enough?
One file is fine while you’re learning, and the FastAPI tutorial for beginners stays in one file for that reason. I start splitting when any of these show up:
- The file passes about 150 lines and you keep searching for routes.
- You have two or more resources, like books and authors.
- Settings such as a title or page size are scattered through the code.
- You want tests that import the app without starting a server.
That 150 is my habit, not a FastAPI rule. FastAPI doesn’t force any layout, so the structure below is simply one that stays readable and is easy to grow.
The FastAPI project structure I use for small apps
Here’s the complete Liberty Books project, printed by the real tree /F /A command in Command Prompt. It has 14 files, and six of them are empty:
bookstore
| .env
|
+---app
| | main.py
| | __init__.py
| |
| +---core
| | config.py
| | __init__.py
| |
| +---models
| | book.py
| | __init__.py
| |
| +---routers
| | authors.py
| | books.py
| | __init__.py
| |
| \---schemas
| book.py
| __init__.py
|
\---tests
test_books.py
__init__.py

__init__.py.| Path | What goes in it | What stays out |
|---|---|---|
app/main.py | Creates FastAPI() and includes routers | Business rules and data |
app/routers/ | One file of endpoints per resource | Settings values |
app/schemas/ | Pydantic shapes for JSON in and out | Stored data |
app/models/ | How data is stored: dataclasses now, database tables later | HTTP details |
app/core/ | App-wide settings | Anything that imports a router |
tests/ | Tests that import app.main | Production code |
Weighing what kind of Python project to build in the first place? Building apps with Python compares the options before you commit to an API.
Create the folders and __init__.py files
Start in an empty folder with FastAPI installed; installing FastAPI and creating your first API covers the virtual environment. Then add the settings library, which fastapi[standard] doesn’t pull in, and create the skeleton. These are Windows commands:
pip install pydantic-settings pytest
mkdir bookstore\app\core bookstore\app\models bookstore\app\schemas bookstore\app\routers bookstore\tests
cd bookstore
type nul > app\__init__.py
type nul > app\core\__init__.py
type nul > app\models\__init__.py
type nul > app\schemas\__init__.py
type nul > app\routers\__init__.py
type nul > tests\__init__.py
An __init__.py marks a folder as a Python package, which is what makes from app.routers import books work. Leave all six empty. On macOS or Linux, use mkdir -p and touch instead.
Add FastAPI settings in app/core/config.py
Same bookstore, first real file. Settings live here so that any module can import them without touching main.py. BaseSettings reads environment variables and a .env file:
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
app_name: str = "Liberty Books API"
default_page_size: int = 2
model_config = SettingsConfigDict(env_file=".env")
settings = Settings()
Create .env in the project root, next to the app folder, and keep it out of Git once it holds secrets:
APP_NAME="Liberty Books API (Boston)"
Note: a relative env_file path is looked up from wherever you start the program. When I imported this config from inside app/, the name silently fell back to “Liberty Books API”, which is one more reason to run from the root.
FastAPI models vs schemas: where each one goes
This split confuses most beginners. A model is how you store a book, and a schema is what a book looks like as JSON. Our model is a dataclass and a list, since a database would only distract from the layout.
from dataclasses import dataclass
@dataclass
class Book:
id: int
title: str
author_id: int
price_usd: float
BOOKS = [
Book(1, "Harbor Lights", 1, 18.99),
Book(2, "The Prairie Ledger", 2, 24.50),
Book(3, "Tides of Maine", 1, 16.75),
]
AUTHORS = {1: "Dana Whitfield", 2: "Marcus Bell"}
BOOKS stays a plain list because lists are mutable, so a POST can append to it while the server runs.
Save that as app/models/book.py. The schemas go in app/schemas/book.py. BookCreate has no id because the client doesn’t choose one, while BookRead adds it for responses:
from pydantic import BaseModel, Field
class BookCreate(BaseModel):
title: str = Field(min_length=1)
author_id: int
price_usd: float = Field(gt=0)
class BookRead(BookCreate):
id: int
Split FastAPI endpoints into app/routers
An APIRouter works like a mini FastAPI app for one resource. I’ll keep it brief here: prefix starts every path in the file and tags groups them in the docs. Save this as app/routers/books.py:
from fastapi import APIRouter, HTTPException
from app.core.config import settings
from app.models.book import BOOKS, Book
from app.schemas.book import BookCreate, BookRead
router = APIRouter(prefix="/books", tags=["books"])
@router.get("/", response_model=list[BookRead])
def list_books(limit: int = settings.default_page_size):
return BOOKS[:limit]
@router.get("/{book_id}", response_model=BookRead)
def get_book(book_id: int):
for book in BOOKS:
if book.id == book_id:
return book
raise HTTPException(status_code=404, detail="Book not found")
@router.post("/", response_model=BookRead, status_code=201)
def add_book(new_book: BookCreate):
book = Book(id=len(BOOKS) + 1, **new_book.model_dump())
BOOKS.append(book)
return book
The lookup in get_book is just a Python for loop, and the int hint is why the value arrives as a real integer.
The imports show the whole idea of the layout: the router pulls settings from core, data from models and shapes from schemas. A second, smaller router goes in app/routers/authors.py:
from fastapi import APIRouter
from app.models.book import AUTHORS
router = APIRouter(prefix="/authors", tags=["authors"])
@router.get("/")
def list_authors():
return AUTHORS
Connect the routers in FastAPI main.py
With the work moved out, main.py gets short. It creates the app, includes each router and keeps one health check:
from fastapi import FastAPI
from app.core.config import settings
from app.routers import authors, books
app = FastAPI(title=settings.app_name)
app.include_router(books.router)
app.include_router(authors.router)
@app.get("/health")
def health():
return {"status": "ok", "app": settings.app_name}
Notice that imports all flow one way: main imports routers, and routers import core, models and schemas. Nothing imports main except the tests. Keeping that direction prevents most import headaches.
settings is a module-level name, so its scope is the whole module and every importer shares one object.
How do you run a multi-file FastAPI project?
Open a terminal in the bookstore folder, the one that contains app, and run:
fastapi dev app/main.py
Using import string: app.main:app
Server started at http://127.0.0.1:8000
INFO: Application startup complete.
The line to check is Using import string: app.main:app, which means the package was found.

Application startup complete means every import in the package resolved.The CLI walks up through folders containing __init__.py to find the package root, then imports app.main:app. If you’d rather type only fastapi dev, add this to a pyproject.toml in the root. I tested that too, and it picked the same import string:
[tool.fastapi]
entrypoint = "app.main:app"
With the server running, this small script calls every part of the package. It uses httpx, which the standard extras install, and you can save it anywhere:
import httpx
BASE = "http://127.0.0.1:8000"
print(httpx.get(f"{BASE}/health").json())
print(httpx.get(f"{BASE}/books/").json())
print(httpx.get(f"{BASE}/authors/").json())
book = {"title": "Cedar Creek Almanac", "author_id": 2, "price_usd": 21.00}
created = httpx.post(f"{BASE}/books/", json=book)
print(created.status_code, created.json())
print(httpx.get(f"{BASE}/books/99").status_code)
Output:
{'status': 'ok', 'app': 'Liberty Books API (Boston)'}
[{'title': 'Harbor Lights', 'author_id': 1, 'price_usd': 18.99, 'id': 1}, {'title': 'The Prairie Ledger', 'author_id': 2, 'price_usd': 24.5, 'id': 2}]
{'1': 'Dana Whitfield', '2': 'Marcus Bell'}
201 {'title': 'Cedar Creek Almanac', 'author_id': 2, 'price_usd': 21.0, 'id': 4}
404
The health check reads the .env name, the default page size returns 2 of the 3 books, and Cedar Creek Almanac is saved as book 4 at $21.00. Book 99 gets the 404 from get_book.
Now open http://127.0.0.1:8000/docs. Both routers appear under their own tag, which is a quick visual check that include_router ran:

tags value becomes its own section in Swagger UI.Expand GET /books/{book_id}, click Try it out, enter 2 and click Execute. The request travels through the router, the model list and the schema:

BookRead.Test the package from the tests folder
A separate tests folder works because the tests import the package exactly as the server does. TestClient calls the app without a running server. Save this as tests/test_books.py:
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
def test_get_book():
response = client.get("/books/2")
assert response.status_code == 200
assert response.json()["title"] == "The Prairie Ledger"
def test_missing_book_returns_404():
assert client.get("/books/999").status_code == 404
Run it from the project root. If your team needs identical results, pin the pytest version when you install it:
python -m pytest -q
.. [100%]
2 passed in 0.60s

Absolute or relative imports in FastAPI?
Both work inside a package. The official FastAPI guide uses relative imports, and I use absolute ones with beginners because each line tells you exactly where the file is:
| Style | In app/routers/books.py | Reads as |
|---|---|---|
| Absolute | from app.core.config import settings | Start at the project root |
| Relative | from ..core.config import settings | Go up one package from routers |
Pick one style per project. Python searches its import path for the first name, and this ModuleNotFoundError guide explains that search for installed packages.
Common FastAPI import errors and how to fix them
Every message below came from breaking this same project on purpose. The first two account for most of the trouble I see.
ModuleNotFoundError: No module named ‘app’
Running the file directly is the classic cause. Python then puts app/ itself on the path, so the name app can’t be found:
python app/main.py
Traceback (most recent call last):
File "C:\pyguides\bookstore\app\main.py", line 3, in <module>
from app.core.config import settings
ModuleNotFoundError: No module named 'app'

main.py as a script breaks the package import.Fix: start it with fastapi dev app/main.py from the project root. Deleting app/__init__.py gave me the same error under fastapi dev, because the CLI then treats app/ as the root. Put that file back.
One surprise from testing: removing only app/routers/__init__.py didn’t break anything, because Python treats it as a namespace package. I’d still keep it, since tools and teammates expect it.
ImportError: partially initialized module (circular import)
A circular import means two modules need each other while still loading. Add this one bad line to app/routers/books.py:
from app.main import app # books.py importing main, while main imports books
ImportError: cannot import name 'app' from partially initialized module 'app.main' (most likely due to a circular import)

main is still on its router import, so app doesn’t exist yet.Fix: never import main from a router. Move whatever both files need into core, models or schemas. This is timing-dependent too: importing settings from main happened to work for me, but only because of the line order, so don’t rely on it.
A router’s endpoints are missing
Importing the router variable from two files means the second import replaces the first. Both include_router calls then add the same router, with no error at all:
from app.routers.books import router
from app.routers.authors import router
# paths in the app:
['/authors/', '/health']
Fix: import the modules, as in from app.routers import authors, books, then use books.router and authors.router.
A path prefix must not end with ‘/’
Writing prefix="/books/" stops the app at import with this message:
AssertionError: A path prefix must not end with '/', as the routes will start with '/'
Fix: drop the trailing slash, because each route path already starts with one.
Tests fail with No module named ‘app’
Without tests/__init__.py, a bare pytest failed for me while python -m pytest passed, because the -m form adds the current folder to the path. Keep the file and use the -m form.
When should you change this FastAPI layout?
This folders-by-type layout suits a handful of resources. Once you have many, group by feature instead, such as app/books/ holding its own router, schemas and models. For shipping it, this FastAPI and Docker deployment walkthrough is a useful next read.
If you’re working through FastAPI in order, these pages pick up from here:
Frequently asked questions
What is the best FastAPI project structure for beginners?
One app package with main.py and folders for routers, schemas, models and core, plus a tests folder beside it. It’s simple and leaves room to grow.
Do I need __init__.py files in a FastAPI project?
Keep them in every code folder. Without app/__init__.py, fastapi dev app/main.py failed in my test with No module named 'app'.
What’s the difference between models and schemas in FastAPI?
Models describe how data is stored, and schemas describe the JSON your API accepts and returns. Keeping them apart stops storage-only fields from leaking into responses.
How do I fix a circular import in FastAPI?
Make imports flow one way. Routers must not import main; move shared code into a module such as core/config.py that imports neither.
Where does the official FastAPI documentation cover multiple files?
The Bigger Applications guide explains packages, APIRouter, imports and the entrypoint setting.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn