FastAPI 核心基础知识速览
一、FastAPI 概述
FastAPI 是一个基于 Python 的高性能 Web 框架,专为快速构建 API 服务而设计。其核心优势在于原生异步支持与自动数据校验。
| 对比维度 | FastAPI | Flask | Django |
|---|---|---|---|
| 性能 | 高(原生异步) | 中等 | 较低(同步) |
| 异步支持 | 内置 async/await | 需第三方扩展 | 非原生支持 |
| 数据验证 | Pydantic 自动校验 | 手动实现 | ORM 级别验证 |
| 自动文档 | 自动生成 | 需插件 | 需扩展 |
| 适用场景 | API、微服务、AI 推理 | 小型 Web 应用 | 大型网站 |
二、快速入门示例
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def home():
return {"message": "Hello World"}
@app.get("/users/{user_id}")
async def get_user(user_id: int, name: str | None = None):
return {"user_id": user_id, "name": name}
三、路由机制
路由定义了 URL 与处理函数之间的映射关系。当客户端访问指定 URL 时,服务器调用对应的函数返回结果。FastAPI 使用 Python 装饰器模式实现路由定义。
四、参数分类
参数让同一接口根据输入不同返回不同数据,实现动态交互。
- 路径参数:位于 URL 路径中(如
/items/{id}),用于标识特定资源,通常用于 GET 请求。 - 查询参数:位于 URL 的
?之后(如?page=1&size=10),用于过滤、排序或分页,通常用于 GET 请求。 - 请求体参数:位于 HTTP 请求的 body 中,用于创建或更新资源,通常用于 POST、PUT 请求。
五、路径参数校验:Path
使用 Path 类型注解可以为路径参数添加额外校验和描述。
| 参数 | 说明 |
|---|---|
... |
必填 |
gt / ge |
大于 / 大于等于 |
lt / le |
小于 / 小于等于 |
description |
描述信息 |
min_length / max_length |
长度限制 |
六、查询参数校验:Query
当参数不是路径参数时,FastAPI 自动将其解释为查询参数。校验方式与 Path 相同,支持 gt、ge、lt、le、description、min_length、max_length 等。
七、请求体参数校验:Field
HTTP 请求由三部分组成:请求行(方法、URL、协议版本)、请求头(元数据)、请求体(实际数据)。请求体参数用于创建或更新资源。
| 参数 | 说明 |
|---|---|
... |
必填 |
gt / ge |
大于 / 大于等于 |
lt / le |
小于 / 小于等于 |
default |
默认值 |
description |
描述信息 |
min_length |
最小长度 |
max_length |
最大长度 |
八、响应类型
请求响应过程
客户端发送请求,FastAPI 处理后返回响应。默认情况下,FastAPI 自动将 Python 对象(字典、列表、Pydantic 模型)转换为 JSON 格式并包装为 JSONResponse。
常见响应类型
| 响应类型 | 用途 | 示例 |
|---|---|---|
| JSONResponse | 默认 JSON 响应 | return {"key": "value"} |
| HTMLResponse | 返回 HTML 内容 | return HTMLResponse(html_content) |
| PlainTextResponse | 返回纯文本 | return PlainTextResponse("text") |
| FileResponse | 返回文件下载 | return FileResponse(path) |
| StreamingResponse | 流式响应 | 生成器函数返回数据 |
| RedirectResponse | 重定向 | return RedirectResponse(url) |
设置响应类型的方式
- 装饰器参数:适用于固定返回类型。
from fastapi.responses import HTMLResponse
@app.get("/page", response_class=HTMLResponse)
async def get_page():
return "<h1>Welcome</h1>"
- 直接返回响应对象:适用于文件、图片、流式响应等。
from fastapi.responses import FileResponse
@app.get("/download")
async def download_file():
path = "./assets/report.pdf"
return FileResponse(path)
九、自定义响应格式:response_model
response_model 是路由装饰器的关键参数,通过 Pydantic 模型严格定义输出格式,实现数据验证与安全控制。
from pydantic import BaseModel
class Article(BaseModel):
id: int
title: str
body: str
@app.get("/articles/{id}", response_model=Article)
async def get_article(id: int):
return {
"id": id,
"title": f"Article {id}",
"body": "This is the content"
}
注意:响应数据必须符合定义的模型格式,否则会触发验证错误。
十、异常处理
对于客户端错误(如 404 资源未找到、401 认证失败),应使用 fastapi.HTTPException 中断正常流程并返回标准错误响应。
from fastapi import FastAPI, HTTPException
app = FastAPI()
VALID_IDS = [1, 2, 3, 4, 5]
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if item_id not in VALID_IDS:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}