推荐项目结构your_project/├── .env # 环境变量(数据库、密钥等)
├── .gitignore
├── main.py # 项目入口(挂载所有路由、配置中间件)
├── requirements.txt # 依赖清单
├── app/ # 核心应用包
│ ├── __init__.py
│ ├── core/ # 核心配置(全局配置、依赖、异常)
│ │ ├── __init__.py
│ │ ├── config.py # 项目配置(读取.env)
│ │ ├── dependencies.py # 全局依赖(数据库会话、认证等)
│ │ └── exceptions.py # 全局异常处理
│ ├── api/ # API 路由层(所有接口)
│ │ ├── __init__.py
│ │ ├── api_v1/ # 版本化路由(v1)
│ │ │ ├── __init__.py
│ │ │ ├── endpoints/ # 接口模块(按业务拆分)
│ │ │ │ ├── __init__.py
│ │ │ │ ├── users.py # 用户相关接口
│ │ │ │ └── items.py # 商品相关接口
│ │ │ └── api.py # 聚合v1所有路由
│ ├── models/ # 数据模型层
│ │ ├── __init__.py
│ │ ├── database.py # 数据库连接(SQLAlchemy)
│ │ └── schemas/ # Pydantic模型(请求/响应校验)
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── item.py
│ ├── crud/ # 数据操作层(Create/Read/Update/Delete)
│ │ ├── __init__.py
│ │ ├── base.py # 通用CRUD基类
│ │ ├── crud_user.py
│ │ └── crud_item.py
│ ├── services/ # 业务逻辑层(核心!解耦路由和数据)
│ │ ├── __init__.py
│ │ ├── user_service.py
│ │ └── item_service.py
│ └── utils/ # 工具函数(日志、加密、时间等)
│ ├── __init__.py
│ ├── logger.py
│ └── security.py
└── tests/ # 测试用例
├── __init__.py
├── conftest.py
├── test_users.py
└── test_items.py
main.py —— 项目入口
创建 FastAPI 实例、挂载路由、添加中间件、配置异常处理器。
from fastapi import FastAPIfrom app.api.api_v1.api import api_router
from app.core.config import settings
app = FastAPI(title=settings.PROJECT_NAME)
# 挂载版本化路由
app.include_router(api_router, prefix=f"/api/{settings.API_VERSION}")
@app.get("/")
def root():
return {"message": "Hello FastAPI"}
app/core/ —— 核心配置
config.py:统一管理所有配置(读取 .env)dependencies.py:全局依赖(数据库会话、Token 认证)exceptions.py:自定义异常 + 全局异常处理器from pydantic_settings import BaseSettingsclass Settings(BaseSettings):
PROJECT_NAME: str = "FastAPI Project"
API_VERSION: str = "v1"
DATABASE_URL: str
SECRET_KEY: str
Config:
env_file = ".env"
settings = Settings()
app/api/ —— 路由层(接口入口)
定义接口路径、请求方法接收请求参数(用 Pydantic 校验)调用 service 层,返回响应不写业务逻辑!from fastapi import APIRouter, Dependsfrom app.schemas.user import UserCreate, UserResponse
from app.services.user_service import UserService
router = APIRouter()
@router.post("/", response_model=UserResponse)
def create_user(user: UserCreate, service: UserService = Depends()):
return service.create_user(user)
app/services/ —— 业务逻辑层(核心)
所有业务规则都写在这里,是项目的灵魂。
路由只转发,CRUD 只操作数据库,service 做中间处理。
from app.crud.crud_user import user_crudfrom app.schemas.user import UserCreate
from app.models.database import get_db
from sqlalchemy.orm import Session
class UserService:
def __init__(self, db: Session = Depends(get_db)):
self.db = db
self.crud = user_crud
def create_user(self, user_in: UserCreate):
# 业务逻辑:检查邮箱是否重复
if self.crud.get_by_email(self.db, email=user_in.email):
raise ValueError("邮箱已存在")
return self.crud.create(self.db, obj_in=user_in)
app/crud/ —— 数据访问层
只做纯数据库操作:增删改查,无任何业务逻辑。
app/models/schemas/ —— Pydantic 模型
请求体校验响应模型格式化自动生成接口文档app/utils/ —— 工具函数
通用工具:密码加密、JWT 生成、日志、时间格式化等。
3 条 FastAPI 黄金规则路由层不写业务逻辑业务逻辑全部写在 Service 层CRUD 只做数据库操作遵循这个结构,你的项目:
多人协作不混乱方便单元测试方便扩展新接口方便迁移、重构总结用分层架构:路由 → 服务 → 数据访问
用版本化路由:/api/v1/xxx用Pydantic做参数校验用 **.env** 管理环境变量业务逻辑全部放入 service