【FastAPI】请求参数全解析:路径参数、查询参数、请求体参数 详解 + 原生注解 vs 函数类型注解

张开发
2026/4/10 10:42:50 15 分钟阅读

分享文章

【FastAPI】请求参数全解析:路径参数、查询参数、请求体参数 详解 + 原生注解 vs 函数类型注解
《FastAPI 请求参数全解析路径参数、查询参数、请求体参数 详解 原生注解 vs 函数类型注解附完整代码 易错点》文章前言在 FastAPI 开发中正确使用路径参数、查询参数、请求体参数是构建高效、安全、可维护 API 的基础。很多开发者容易混淆“原生注解”与“函数类型注解”的使用方式导致422 错误、API 文档缺失、类型不校验等问题。本文通过代码实操 详细注释 知识点总结 易错点警示带你系统掌握路径参数Path(...)用法查询参数Query(...)用法请求体参数BaseModel Field(...)用法每个参数的完整函数类型注解写法如path(...),field(...)等一、基础路由1. 原生注解app.get(/)asyncdefroot():return{message:Hello World888}app.get(/hello)asyncdefhello():return{msg:你好 FastAPI}app.get(/user/hello)asyncdefhello_user():return{msg:我正在学习 FastAPI...}知识点app.get(/)定义 GET 请求路径async def异步函数支持高并发返回dictFastAPI 自动转为 JSON易错点不能返回str或int必须返回dict或list不能用print()输出应使用logging2. 函数的类型注解无- dict仅保留函数结构app.get(/)asyncdefroot():return{message:Hello World888}app.get(/hello)asyncdefhello():return{msg:你好 FastAPI}app.get(/user/hello)asyncdefhello_user():return{msg:我正在学习 FastAPI...}此部分不添加- dict与原生注解一致保持简洁FastAPI 通过返回值自动推断类型无需显式声明知识点async def不需要-返回类型FastAPI 自动识别无需- dict代码更简洁更符合实际开发习惯易错点返回None会导致500错误 → 应返回空字典{}或{msg: }若 IDE 报错可开启pydantic-settingstype-checking插件二、路径参数1. 原生注解app.get(/book1/{id})asyncdefget_book_by_id(id:int):return{id:id,title:f这是第{id}本书}app.get(/square/{num})asyncdefsquare(num:int):return{输入数字:num,平方结果:num**2}知识点{id}路径变量自动绑定为函数参数id: int原生类型自动转换为整数无需手动解析自动完成易错点参数名写错如id1会导致路径不匹配不写类型 →id: Any无校验、无 Swagger 表单2. 函数的类型注解结合Path(...)无- dictapp.get(/book2/{id})asyncdefget_book_with_validation(id:intPath(...,gt0,le100,description书籍ID必须是 1~100 之间的整数)):return{id:id,title:f这是第{id}本书}app.get(/author/{name})asyncdefget_name(name:strPath(...,min_length5,max_length10,description作者名称)):return{作者:name}知识点Path(...)显式声明路径参数支持校验gt0, le100数值范围校验不满足返回 422min_length,max_length字符串长度控制description显示在 Swagger 文档中不写- dict保持代码简洁易错点Path(...)要写在右端如int Path(...)不是id: Path(...)否则语法错误max_length10, min_length5写成max_length10,min_length5→ 缺少逗号报错Path(..., ...)中永远不要混用Field(...)Path不支持Field三、查询参数1. 原生注解app.get(/news/news_list)asyncdefget_news_list(page:int1,size:int10):return{page:page,size:size}知识点page: int 1默认值可选参数查询字符串拼接?page1size10自动类型转换如字符串转整数易错点不设默认值 → 参数必填用户不传会报错用int 1而不用Query→ 无校验、无文档2. 函数的类型注解结合Query(...)无- dictapp.get(/news1/news_list)asyncdefget_news_list(page:intQuery(1,lt100,description页码),size:intQuery(10,ge5,le50,description每页数量)):return{page:page,size:size}app.get(/book/book_list)asyncdefget_book_list(category:strQuery(python,min_length5,max_length255,description图书分类),price:intQuery(50,ge50,le100,description图书价格)):return{图书分类:category,图书价格:price}知识点Query(...)显式定义查询参数支持校验与文档描述lt100小于 100ge5大于等于 5description生成 Swagger 表单说明不写- dictFastAPI 自动识别返回类型易错点Query(10, ge5, le50)会冲突10 满足ge5但不满足le50→ 不违规但会报错文本Query(python, max_length255)可以但Query(python, min_length5)时需确保值 ≥5 字符Query(...)不能写在dict外部必须作为参数默认值四、请求体参数1. 原生注解使用BaseModelclassUser(BaseModel):username:strpassword:strapp.post(/user/register)asyncdefregister(user:User):return{username:user.username,password:user.password}知识点BaseModel定义请求体数据结构user: UserFastAPI 自动解析application/json请求体字段未加Field(...) 必填...自动添加易错点BaseModel类重复定义 → 报错请求体格式错误如username: 123→ 返回422提示字段类型错误2. 函数的类型注解结合Field(...)无- dictclassEmployee(BaseModel):name:strField(...,min_length2,max_length10,description员工姓名)age:intField(...,ge18,le60,description员工年龄)salary:floatField(...,gt5000,lt10000,description员工薪资)app.post(/employee)asyncdefsearch_employee(employee:Employee):return{name:employee.name,age:employee.age,salary:employee.salary}classBook(BaseModel):name:strField(...,min_length5,max_length255,description图书名称)price:intField(...,ge50,le100,description图书价格)category:strField(...,min_length5,max_length255,description图书分类)author:strField(...,min_length5,max_length255,description图书作者)publish_date:strField(...,min_length5,max_length255,description图书出版日期)publish_house:strField(黑马出版社,min_length5,max_length255,description图书出版社)app.post(/book)asyncdefsearch_book(book:Book):return{name:book.name,price:book.price,category:book.category,author:book.author,publish_date:book.publish_date,publish_house:book.publish_house}知识点Field(...)显式设置数据校验规则必填、长度、范围...表示字段必填带默认值的字段如publish_house可省略...不写- dictFastAPI 自动推断返回类型FastAPI 自动校验并返回422错误如 price40 →ge50不满足易错点❌Field(默认值, max_length255)写错顺序 → 正确顺序是max_length255❌Field(..., min_length5)但传入空字符串 → 返回 422❌Field写在BaseModel外部 → 语法错误❌Field(..., max_length255)与str xxxx冲突时优先校验长度

更多文章