Documents
Home>Documents>Dev>Backend

FastAPI Project Structure Best Practices

5 min readJun 15, 2025Feb 22, 2026

FastAPI Project Structure

This document summarizes the FastAPI project structure used across hr_blog2.0, PlateeRAG_backend-1, web-backend, and similar projects.

graph TD
    A[src/] --> B[main.py]
    A --> C[db.py]
    A --> D[schemas.py]
    A --> E[storage.py]
    A --> F[controllers/]
    A --> G[models/]

    F --> F1[auth.py]
    F --> F2[post.py]
    F --> F3[category.py]
    F --> F4[image.py]

    G --> G1[base.py]
    G --> G2[post.py]
    G --> G3[category.py]

main.py - Application Entry Point

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from controllers import auth, post, category, image

app = FastAPI(title="Blog API", version="1.0.0")

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 라우터 등록
app.include_router(auth.router, prefix="/api/v1")
app.include_router(post.router, prefix="/api/v1")
app.include_router(category.router, prefix="/api/v1")
app.include_router(image.router, prefix="/api/v1")

schemas.py - Pydantic Models

from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime

class PostCreate(BaseModel):
    slug: str
    title: str
    content: str
    category: str
    tags: List[str] = []
    read_time: int = 5
    published: bool = True
    password: str
    created_at: Optional[datetime] = None
    connections: List[str] = []

Dependency Injection

from fastapi import Depends
from sqlalchemy.orm import Session

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.get("/posts")
def list_posts(db: Session = Depends(get_db)):
    return db.query(Post).all()

Core Principles

  1. Separation of concerns: Keep controllers, models, and schemas in separate layers
  2. Dependency injection: Use patterns like get_db and get_current_user
  3. Modular routers: Split routers into dedicated files per feature
  4. Pydantic validation: Define schemas for both request inputs and response outputs
  5. Auto-generated docs: Swagger UI available out of the box at /docs
Tags
FastAPIproject structurePythonREST APIbest practices