FastAPI的接口实现流程讲解

fastapi的接口实现主要经过下面几个流程:

  1. 模块化路由
  2. 定义模型类
  3. 数据库
  4. 路由调用逻辑

下面就一步步讲解每个流程:


1.模块化路由

1.首先定义APIRouter实例

用 APIRouter 把接口按业务模块拆分,比如用户、订单、商品各一个路由文件。

python 复制代码
from fastapi import APIRouter

router = APIRouter(prefix="/users", tags=["users"])

@router.get("/{user_id}")
async def get_user(user_id: int):
    ...

2.注册路由

然后在 main.py里挂载:

python 复制代码
app.include_router(user_router)

3.参照接口规范文档


2.定义模型类

这里通常有两类模型:

模型类型 作用 例子
ORM 模型 映射数据库表 User
Pydantic 模型 校验请求、规范响应 UserCreate、UserResponse

下面是示例代码:

python 复制代码
from pydantic import BaseModel

class UserCreate(BaseModel):
    username: str
    email: str

class UserResponse(BaseModel):
    id: int
    username: str
    email: str

    class Config:
        from_attributes = True

具体的可以参考数据库表


3.数据库部分

数据库层主要做三件事:

  • 配置连接,比如 SQLAlchemy 引擎;
  • 创建会话工厂,比如 SessionLocal;
  • 提供 get_db 依赖,让路由里能拿到数据库会话。
python 复制代码
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

4.路由调用逻辑

1.Depends注入数据库依赖

2.调用逻辑

3.响应结果

示例代码:

python 复制代码
@router.post("/", response_model=UserResponse)
async def create_user(user: UserCreate, db: Session = Depends(get_db)):
    db_user = User(username=user.username, email=user.email)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
相关推荐
在世修行21 小时前
干货:文件上传端点解析
python·fastapi·接收上传
云和数据.ChenGuang1 天前
JAVAEE AI工程师路线图
java·人工智能·java-ee·fastapi·springai·langchain4j
风早爽太2 天前
Python 学习笔记:SQLModel 使用外键关联查询数据
python·fastapi·sqlmodel
风早爽太2 天前
Python 学习笔记:数据库迁移工具 ‌Alembic
数据库·python·fastapi·alembic
Web3&Basketball3 天前
用FastAPI+Redis 复刻常驻Agent
redis·bootstrap·fastapi
风早爽太5 天前
Python 开发笔记:配置生产环境中 Celery Worker 的独立进程启动方式
python·fastapi
Java的搬运工7 天前
【无标题】
python·机器学习·docker·fastapi·模型部署·mlops·ai工程化
云和数据.ChenGuang7 天前
langchain4j的RAG入门
人工智能·深度学习·机器学习·语言模型·fastapi
风早爽太8 天前
用 ‌Render‌ 快速部署网站和常见问题解决
python·fastapi