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
相关推荐
hhb_61816 小时前
FastAPI接口开发与性能优化实战
性能优化·fastapi
程序猿乐锅18 小时前
【从0-1学习Python | 第九篇】继承
开发语言·后端·python·学习·fastapi
外收内放2 天前
FastAPI猜字谜实战(4):让AI主持人开口
开发语言·python·学习·fastapi
外收内放2 天前
FastAPI猜字谜实战(6):日志与异常
开发语言·python·学习·fastapi
小林ixn2 天前
用 FastAPI + SQLAlchemy 从零手搓一个博客系统:一套能落地、能讲清楚的 RESTful 后端
后端·python·fastapi
外收内放2 天前
FastAPI猜字谜实战(5):会话管理
开发语言·python·学习·fastapi
Sakura_j_h_2 天前
给 FastAPI 接大模型:超时、重试和 token 成本该怎么管
python·大模型·fastapi·超时重试·token计费
小林ixn3 天前
FastAPI + LangChain 实战:从 0 到 1 打造高性能 AI 后端服务
人工智能·langchain·fastapi
ratel️4 天前
小墨析 · Office Agent 日常办公不烧心
python·langchain·word·excel·fastapi·js·ppt
外收内放4 天前
FastAPI猜字谜实战(3):把每一局存成JSON
开发语言·python·学习·json·fastapi