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
相关推荐
LK_078 天前
【FastAPI】基础篇 01|开始之前:API、HTTP 与 FastAPI 到底是什么
网络协议·http·fastapi
一枕槐安48713 天前
Qwen 通义千问本地部署与推理服务封装
fastapi·qwen·vllm·流式推理·openai兼容api·awq量化
在努力的前端小白13 天前
基于FastAPI+LangChain+LangGraph+Agent+多模态的AI Agent 有渔渔具网站
人工智能·langchain·vue·fastapi
sun_weitao14 天前
用 FastAPI + MQTT 做一个 ESP32最小化跑通示例
中间件·vue·fastapi
峯58014 天前
一文学习FastAPI
学习·fastapi
TheBestRucy16 天前
从零构建企业级“中文法律智能问答系统”:FastAPI+Milvus+混合检索+真流式RAG实战
fastapi·milvus
卡提西亚17 天前
FastAPI基础入门
python·fastapi
Paper-Tiger17 天前
手搓 FastAPI + Redis + 流式 RAG 实录
fastapi
像风一样自由202017 天前
2.如何用FastAPI把一个Python算法封装成HTTP服务
python·算法·fastapi
狗凯之家源码网17 天前
iOS C2 V2 与 Python FastAPI 全链路远控系统深度评测
python·ios·fastapi