Python FastAPI 介绍以及常用方法

FastAPI 完整使用指南 + 常用示例

FastAPI 是一个高性能、工程化的 Python Web API 框架,基于标准 Python 类型提示开发,底层依赖 Starlette(ASGI 异步底层)Pydantic(自动数据校验),原生支持自动生成交互式 API 文档,性能接近 Go/Node.js,是当前 Python 后端 RESTful API 开发的主流方案。


前置安装

需要安装 FastAPI 本体 + ASGI 运行服务器 Uvicorn:

bash 复制代码
pip install fastapi uvicorn

一、最小入门示例

创建 main.py 文件:

python 复制代码
from fastapi import FastAPI

# 创建 FastAPI 应用实例
app = FastAPI(title="示例接口", version="1.0")

# 定义 GET 接口,路径为 /
@app.get("/")
def hello():
    return {"message": "Hello FastAPI"}

启动服务

在终端执行命令(main 是文件名,app 是代码中的实例名):

bash 复制代码
uvicorn main:app --reload
  • --reload:开发环境热重载,代码修改后自动重启,生产环境禁用。
  • 默认地址:[http://127.0.0.1:8000](http://127.0.0.1:8000)

核心特性:自动生成接口文档

启动后直接访问以下地址,可在线调试接口:

  • Swagger UI 交互式文档:[http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
  • ReDoc 文档:[http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)

二、路径参数(Path Parameters)

把参数写在 URL 路径中,支持自动类型校验和转换。

python 复制代码
from fastapi import FastAPI

app = FastAPI()

# 路径参数 item_id,自动约束为 int 类型
@app.get("/items/{item_id}")
def get_item(item_id: int):
    return {"item_id": item_id, "name": f"商品{item_id}"}

说明

  1. 传入 item_id=123 自动识别为整数;传入非数字字符串会直接返回 422 校验错误,无需手动判断。
  2. 支持枚举限定参数取值范围:
python 复制代码
from enum import Enum
from fastapi import FastAPI

app = FastAPI()
class Category(str, Enum):
    food = "food"
    book = "book"
    electronic = "electronic"

@app.get("/category/{cate}")
def get_category(cate: Category):
    return {"category": cate.value}

只能传入 food/book/electronic 三个值,其他值自动校验失败。


三、查询参数(Query Parameters)

URL 中 ? 后面的参数,直接在函数中定义即可自动解析。

python 复制代码
from enum import Enum
from fastapi import FastAPI

app = FastAPI()
@app.get("/goods/")
def get_goods(skip: int = 0, limit: int = 10, keyword: str | None = None):
    """
    商品列表接口
    - skip: 起始偏移量,默认0
    - limit: 每页数量,默认10
    - keyword: 搜索关键词,可选参数
    """
    return {"skip": skip, "limit": limit, "keyword": keyword}

http://127.0.0.1:8000/goods/?skip=1&limit=2&keyword=3

特点

  • 有默认值的参数为可选参数,无默认值则为必填。
  • 布尔类型自动转换:?active=true?active=1?active=True 都会识别为 True

四、请求体:结合 Pydantic 自动校验

POST/PUT 请求的 JSON 体,配合 Pydantic 的 BaseModel 实现自动解析 + 数据校验。

python 复制代码
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

# 定义请求体模型
class UserCreate(BaseModel):
    username: str = Field(min_length=3, max_length=20)
    age: int = Field(gt=0, lt=120)
    email: str
    password: str = Field(min_length=6)

# POST 接口,参数类型声明为 Pydantic 模型即可
@app.post("/users/", status_code=201)
def create_user(user: UserCreate):
    # 业务逻辑:保存用户等
    return {
        "code": 0,
        "msg": "创建成功",
        "data": {"username": user.username, "age": user.age}
    }

说明

  • FastAPI 自动从请求中读取 JSON,转换为 UserCreate 对象,并执行校验。
  • 校验不通过时自动返回 422 错误和详细的错误信息,无需手动写 if 判断。

五、参数精细化校验:Path / Query

针对路径参数和查询参数,使用 PathQuery 实现更精细的校验规则(和 Pydantic 的 Field 用法一致)。

python 复制代码
from fastapi import FastAPI, Path, Query

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(
    # 路径参数校验:必须大于0
    item_id: int = Path(gt=0, description="商品ID,必须大于0"),
    # 查询参数校验:字符串长度1-50,可选
    q: str | None = Query(default=None, min_length=1, max_length=50)
):
    return {"item_id": item_id, "q": q}
python 复制代码
from fastapi import Header, Cookie

@app.get("/header/")
def get_header(
    user_agent: str | None = Header(default=None),  # 获取请求头 User-Agent
    session_id: str | None = Cookie(default=None)   # 获取 Cookie 中的 session_id
):
    return {"user_agent": user_agent, "session_id": session_id}

六、响应模型:统一格式 + 字段过滤

通过 response_model 指定返回数据的结构,自动过滤敏感字段(比如密码)、统一返回格式。

python 复制代码
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 请求模型:包含密码
class UserCreate(BaseModel):
    username: str
    password: str
    email: str

# 响应模型:不返回密码
class UserResponse(BaseModel):
    username: str
    email: str

@app.post("/users/", response_model=UserResponse)
def create_user(user: UserCreate):
    # 模拟数据库保存,返回完整用户对象(含密码)
    user_in_db = user.model_dump()
    # 自动按照 UserResponse 过滤字段,密码不会返回给前端
    return user_in_db

即使函数返回了包含 password 的字典,FastAPI 也会自动按照 response_model 裁剪字段,保证数据安全。


七、HTTP 状态码与异常处理

自定义响应状态码

通过 status_code 参数设置接口成功时的状态码,比如 201(创建成功)、204(无内容)。

抛出 HTTP 异常

使用 HTTPException 主动抛出业务异常,返回标准错误响应。

python 复制代码
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/users/{user_id}")
def get_user(user_id: int):
    if user_id <= 0:
        # 抛出 400 错误
        raise HTTPException(status_code=400, detail="用户ID不合法")
    if user_id > 100:
        # 抛出 404 错误
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"user_id": user_id, "name": "测试用户"}

八、依赖注入:逻辑复用(Depends)

FastAPI 的核心特性之一,用于抽离公共逻辑(分页、鉴权、参数解析等),在多个接口中复用。

示例1:通用分页依赖

python 复制代码
from fastapi import FastAPI, Depends

app = FastAPI()

# 定义分页依赖函数
def get_pagination(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

# 接口中注入依赖,自动接收分页参数
@app.get("/goods/")
def get_goods(pagination: dict = Depends(get_pagination)):
    return pagination

示例2:用户鉴权依赖(模拟)

python 复制代码
def get_current_user(token: str | None = Query(default=None)):
    if not token:
        raise HTTPException(status_code=401, detail="未登录")
    return {"user_id": 1, "username": "admin"}

@app.get("/user/info")
def user_info(current_user = Depends(get_current_user)):
    return {"当前用户": current_user}

九、表单数据与文件上传

1. 表单提交(application/x-www-form-urlencoded)

python 复制代码
from fastapi import FastAPI, Form

app = FastAPI()

@app.post("/login/")
def login(username: str = Form(), password: str = Form()):
    return {"username": username, "login": True}

2. 文件上传(multipart/form-data)

推荐使用 UploadFile,支持大文件异步处理、文件名获取、文件大小等。

python 复制代码
from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post("/upload/")
def upload_file(file: UploadFile = File()):
    return {
        "文件名": file.filename,
        "文件类型": file.content_type,
    }

十、路由拆分:APIRouter 模块化

项目变大后,不能把所有接口写在一个文件里,用 APIRouter 按模块拆分路由。

新建 routers/user.py

python 复制代码
from fastapi import APIRouter

router = APIRouter(prefix="/users", tags=["用户模块"])

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

@router.post("/")
def create_user():
    return {"msg": "创建用户"}

主文件 main.py 挂载路由

python 复制代码
from fastapi import FastAPI
from routers.user import router as user_router

app = FastAPI()
# 挂载用户路由
app.include_router(user_router)

十一、常用配置:跨域(CORS)

前后端分离项目必须配置跨域,使用内置中间件实现:

python 复制代码
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 配置允许的源
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境替换为具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

典型应用场景

  1. 前后端分离的后端 RESTful API 开发
  2. 微服务内部接口、数据服务接口
  3. 机器学习模型的 HTTP 服务化封装
  4. 配合 SQLAlchemy / Tortoise-ORM 开发数据库业务系统
相关推荐
论文复现现场1 小时前
企业知识库 RAG 用什么模型便宜?GLM-5.3-Flash 长文本 API 实测
python·rag·企业知识库·大模型api·glm-5.3-flash
梦在远山后1 小时前
从手写 Loop 到可恢复 Runtime:用 LangGraph、PostgreSQL Checkpoint 与 AG-UI 跑通中断恢复
python·langchain·agent
Yolanda_20222 小时前
8.tensorboard的使用
python
用户0332126663672 小时前
使用 Python 添加、隐藏或删除 PowerPoint 幻灯片
python
言乐62 小时前
Python关键词抓取目标网站
python·django·virtualenv·pygame·tornado
用户7783366132112 小时前
搜索页的 URL 状态管理:可分享、可回退、可刷新
python·api
Liaiyang662 小时前
空圈容错视角下的无人机全链路审计:从理论框架到耦合式检验
人工智能·pytorch·python·深度学习·系统架构·自动驾驶·无人机
liuchangng2 小时前
Jev 模型研究:从生成式大模型到决策式模型——System One、RLCD 校准与采用边界
java·javascript·人工智能·python·深度学习
微小冷3 小时前
patsy:Python中的统计建模语法
python·统计·建模·patsy·statmodels