FastAPI 零基础入门教程:从基础到实战响应
FastAPI 零基础入门教程:从基础到实战响应
FastAPI 是现代、快速(高性能)的 Python Web 框架,基于标准 Python 类型注解构建 API,学习成本低、开发效率极高。这篇教程带你从零掌握 FastAPI 核心知识点,包含完整可运行代码。
环境准备
首先安装 FastAPI 和 ASGI 服务器 uvicorn:
pip install fastapi uvicorn=0.21.0
这里,uvicorn最好安装0.21.0版本,最新版的可能会导致热重载延迟的问题。
1. 第一个 FastAPI 程序
创建 main.py,编写最简单的 FastAPI 服务:
# 导入FastAPI核心类
from fastapi import FastAPI
# 创建应用实例
app = FastAPI()
# 定义根路由,处理GET请求
@app.get("/")
def home():
return {"message": "Hello FastAPI!"}
运行命令:
uvicorn main:app --reload
或者点击pycharm的运行按钮:

访问:打开浏览器输入 http://127.0.0.1:8000,就能看到返回的 JSON 数据。自动文档:http://127.0.0.1:8000/docs(FastAPI 自带交互式 API 文档)。
2. 路由(Route)
路由就是URL 路径 + 请求方法(GET/POST/PUT/DELETE),用来匹配客户端请求并执行对应函数。
FastAPI 支持所有常用请求方法:
from fastapi import FastAPI
app = FastAPI()
# GET:获取数据
@app.get("/get")
def get_data():
return {"type": "GET请求"}
# POST:提交数据
@app.post("/post")
def post_data():
return {"type": "POST请求"}
# PUT:更新数据
@app.put("/put")
def put_data():
return {"type": "PUT请求"}
# DELETE:删除数据
@app.delete("/delete")
def delete_data():
return {"type": "DELETE请求"}
3. 参数简介 + 路径参数
3.1 参数分类
- 路径参数:写在 URL 路径里的参数(如 /user/123)
- 查询参数:URL 后缀 ?key=value 形式
- 请求体参数:POST/PUT 提交的 JSON 数据
3.2 路径参数基础
路径参数直接写在路由路径中,用 {} 包裹:
from fastapi import FastAPI
app = FastAPI()
# 定义带路径参数的路由
@app.get("/user/{user_id}")
def get_user(user_id):
return {"用户ID": user_id}
# 返回:{"用户ID":"1001"}
访问:http://127.0.0.1:8000/user/1001
4. 路径参数 + 类型注解
使用 Python 类型注解指定路径参数类型(int/str/float/bool),FastAPI 会自动校验参数类型,类型错误直接返回友好报错。
from fastapi import FastAPI
app = FastAPI()
# 指定user_id为整数类型
@app.get("/book/{book_id}")
# 类型注解:int
def get_book(book_id: int):
return {"书籍ID": book_id, "类型": type(book_id).__name__}
✅ 正确访问:/book/101 → 返回正常数据
❌ 错误访问:/book/abc → FastAPI 自动返回类型错误提示
5. 查询参数 + Query 类型注解
查询参数是 URL 中 ? 后面的键值对,无需修改路由路径,直接在函数参数中定义。
使用 Query 可以:设置默认值、参数校验、参数描述。
from fastapi import FastAPI, Query
app = FastAPI()
# 分页接口:page页码,size每页条数
@app.get("/list")
def get_list(
# 查询参数:必传
page: int,
# 查询参数:默认值10,非必传
size: int = 10,
# Query校验:最大长度10
name: str = Query(None, max_length=10, description="搜索关键词")
):
return {
"页码": page,
"每页条数": size,
"搜索关键词": name
}
访问示例:http://127.0.0.1:8000/list?page=1&name=fastapi
6. 请求体参数
查询 / 路径参数不适合传递大量数据,POST/PUT 请求使用请求体(JSON) 传递数据。
需要使用 Pydantic 的 BaseModel 定义数据结构:
from fastapi import FastAPI
# 导入数据模型基类
from pydantic import BaseModel
app = FastAPI()
# 定义请求体结构
class User(BaseModel):
username: str # 必传
age: int # 必传
email: str # 必传
# POST接口,接收请求体
@app.post("/user/add")
def add_user(user: User):
return {
"msg": "用户添加成功",
"数据": user.dict() # 转字典
}
请求方式:发送 POST 请求,Body 为 JSON:
{
"username": "zhangsan",
"age": 20,
"email": "123@qq.com"
}
7. 请求体参数 + Field 类型注解
Field 和 Query 类似,用于请求体字段的校验(长度、范围、描述等)。
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Product(BaseModel):
# 商品名:最小2字符,最大20字符
name: str = Field(..., min_length=2, max_length=20, description="商品名称")
# 价格:大于0
price: float = Field(..., gt=0, description="商品价格")
# 库存:大于等于0
stock: int = Field(..., ge=0, description="库存数量")
@app.post("/product/add")
def add_product(pro: Product):
return {"数据": pro.dict()}
常用校验规则:
- gt:大于
- ge:大于等于
- lt:小于
- le:小于等于
- min_length/max_length:字符串长度
8. 响应类型:JSON 格式
FastAPI 默认返回 JSON 格式,直接返回字典、列表、Pydantic 模型都会自动转 JSON。
from fastapi import FastAPI
app = FastAPI()
# 返回字典(JSON)
@app.get("/json1")
def json1():
return {"name": "FastAPI", "type": "JSON"}
# 返回Pydantic模型(自动转JSON)
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
@app.get("/json2")
def json2():
return User(name="李四", age=22)
9. 响应类型:HTML 格式
使用 HTMLResponse 直接返回 HTML 页面,适合简单网页渲染。
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
def html():
# 直接返回HTML字符串
return """
<html>
<head><title>FastAPI HTML</title></head>
<body>
<h1>Hello FastAPI HTML</h1>
<p>这是FastAPI返回的HTML页面</p>
</body>
</html>
"""
10. 响应类型:文件格式
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
# 返回图片文件
@app.get("/img")
def get_img():
# 替换为你的文件路径
return FileResponse("test.jpg")
# 返回下载文件
@app.get("/download")
def download_file():
return FileResponse("test.txt", filename="文档.txt")
filename:客户端下载时显示的文件名
11. 自定义响应数据格式
使用 Response 或自定义返回类,实现自定义状态码、响应头、返回格式。
11.1 自定义状态码 + 响应头
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/custom1")
def custom1(response: Response):
# 设置状态码
response.status_code = 201
# 设置自定义响应头
response.headers["Author"] = "FastAPI教程"
return {"msg": "自定义响应"}
11.2 统一自定义响应格式(推荐)
项目中常用:统一返回 code/msg/data 格式:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 定义统一响应模型
class ApiResponse(BaseModel):
code: int = 200
msg: str = "请求成功"
data: dict = None
# 封装统一响应函数
def success(data=None, msg="请求成功"):
return ApiResponse(code=200, msg=msg, data=data)
def error(msg="请求失败", code=400):
return ApiResponse(code=code, msg=msg)
# 使用自定义响应
@app.get("/api/user")
def api_user():
data = {"name": "张三", "age": 23}
return success(data=data)
@app.get("/api/error")
def api_error():
return error(msg="用户不存在", code=404)
返回示例:
{
"code": 200,
"msg": "请求成功",
"data": {
"name": "张三",
"age": 23
}
}
总结
这篇教程完整覆盖 FastAPI 基础核心知识点:
- 快速搭建第一个 FastAPI 服务
- 路由与请求方法(GET/POST/PUT/DELETE)
- 路径参数 + 类型自动校验
- 查询参数 + Query 校验
- 请求体 + BaseModel + Field 校验
- 三种常用响应:JSON / HTML / 文件
- 企业级自定义统一响应格式
所有代码均可直接复制运行,配合 FastAPI 自动文档 http://127.0.0.1:8000/docs 可以快速测试接口。
更多推荐
所有评论(0)