FastAPI教程-请求体参数 作者:马育民 • 2026-08-14 11:15 • 阅读:10001 # 介绍 请求体(Request Body):客户端 `POST`、`PUT`、`PATCH` 把 **JSON、form‑data、文件** 等数据放在请求体内传给接口,**GET 请求没有请求体**。 ### 依赖 依赖 `pydantic` 做数据校验解析,FastAPI 自动 **把请求体解析成 Python 对象**,自动生成 OpenAPI 文档。 ### 应用场景 - 前后端分离项目,前端 `axios`、`fetch` **提交 json** - 参数较多(≥2 个字段),需要自动类型校验、字段约束、接口文档 - 业务上一般是:新增用户、创建订单、提交表单(JSON 格式) 与查询参数不同,查询参数就用来查询、分页等 # 基础用法 模拟实现添加学生信息功能 ### 定义JSON请求体 使用 Pydantic Model 定义 JSON 请求体,用于封装传入的数据,详见[链接](http://www.malaoshi.top/show_1GW3rNYbMqWp.html "链接"): ``` from pydantic import BaseModel # 定义请求体模型 class StudentCreate(BaseModel): name: str age: int sex: str ``` ### 实现处理函数 ``` @app.post('/student') async def create_student(student: StudentCreate): return { 'msg': '添加成功', 'data': student.model_dump() } ``` ### 完整代码 ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # 定义请求体模型 class StudentCreate(BaseModel): name: str age: int sex: str @app.post('/student') async def create_student(student: StudentCreate): return { 'msg': '添加成功', 'data': student.model_dump() } ``` ### 测试:成功 get请求不支持发送请求体,所以要通过Swagger发送POST请求,携带JSON数据 访问:http://127.0.0.1:8000/docs 发送下面数据: ``` { "name": "李雷", "age": 18, "sex":"男" } ``` 如下图: [](http://www.malaoshi.top/upload/0/0/1GW3rNkTerdC.png) [](http://www.malaoshi.top/upload/0/0/1GW3rNkeMEbF.png) ### 测试:不传参数 缺少参数:直接返回422参数校验错误 发送下面数据: ``` { "name": "李雷" } ``` 提示错误: ``` { "detail": [ { "type": "missing", // 错误类型,缺失传参 "loc": [ "body", "age" // 表示求体参数 age 缺少传参 ], "msg": "Field required", // 错误信息,翻译:需要字段 "input": { "name": "李雷" // 表示只输入的内容 } }, { "type": "missing", "loc": [ "body", "sex" ], "msg": "Field required", "input": { "name": "李雷" } } ] } ``` ### 测试:给年龄传abc 缺少参数:直接返回422参数校验错误 发送下面数据: ``` { "name": "李雷", "age":"abc", "sex":"男" } ``` 提示错误: ``` { "detail": [ { "type": "int_parsing", // 错误类型,int解析错误 "loc": [ "body", // 表示求体参数 "age" // 表示求体参数 age 缺少传参 ], "msg": "Input should be a valid integer, unable to parse string as an integer", // 错误信息,应该输入数字类型的内容 "input": "abc" // 实际输入的是 abc } ] } ``` # 设置默认值 添加学生信息时,年龄一般都是 `18` 岁,为了省事方便,设置默认值,不填年龄就取值 `18` 岁。有时只有学生姓名,没有性别信息,那么性别就取值为空,即:`None` ### 定义JSON请求体 使用 Pydantic Model 定义 JSON 请求体,用于封装传入的数据,详见[链接](http://www.malaoshi.top/show_1GW3rNYbMqWp.html "链接"): ``` from pydantic import BaseModel # 定义请求体模型 class StudentCreate(BaseModel): name: str age: int = 18 sex: str | None = None # 可选,默认None ``` ### 实现处理函数 ``` @app.post('/student') async def create_student(student: StudentCreate): return { 'msg': '添加成功', 'data': student.model_dump() } ``` ### 完整代码 ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # 定义请求体模型 class StudentCreate(BaseModel): name: str age: int | None = None # 可选,默认None sex: str @app.post('/student') async def create_student(student: StudentCreate): return { 'msg': '添加成功', 'data': student.model_dump() } ``` ### 测试:不传年龄、性别 发送下面数据: ``` { "name": "李雷" } ``` 结果如下: [](http://www.malaoshi.top/upload/0/0/1GW3rQdNufaS.png) - 年龄 `age` 取默认值 - 性别 `sex` 为null ### 测试:传年龄、性别 发送下面数据: ``` { "name": "李雷", "age":20, "sex":"男" } ``` 结果如下: [](http://www.malaoshi.top/upload/0/0/1GW3rQchEYPO.png) 传什么值,就是什么值 # List / 数组作为请求体 model的字段为数组,比如注册用户时,好多时候要勾选多个 **爱好**, 定义模型,添加爱好: ```json class StudentCreate(BaseModel): name: str age: int sex: str hobby: list[str] # 爱好 ``` ### 处理函数 ```python @app.post('/student') async def create_student(student: StudentCreate): return { 'msg': '添加成功', 'data': student.model_dump() } ``` ### 完整代码 ``` from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # 定义请求体模型 class StudentCreate(BaseModel): name: str age: int sex: str hobby: list[str] # 爱好 @app.post('/student') async def create_student(student: StudentCreate): return { 'msg': '添加成功', 'data': student.model_dump() } ``` ### 测试:成功 发送数据: ``` { "name": "李雷", "age": 18, "sex": "男", "hobby": ["王者荣耀","吃鸡"] } ``` 结果如下图: [](http://www.malaoshi.top/upload/0/0/1GW3rQoTGxT5.png) 原文出处:/show_1GW3rQ7Wo9jA.html