FastAPI 查询参数完全指南:从基础到高级用法 🚀

avatar
cmdragon 渡劫
image image

扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长

探索数千个预构建的 AI 应用,开启你的下一个伟大创意

第一章:查询参数基础

1.1 什么是查询参数?

查询参数是 RESTful API 中用于传递附加信息的变量,通常出现在 URL 的查询字符串中。例如,/items?skip=0&limit=10 中的 skip
limit 就是查询参数。

1
2
3
4
5
6
7
8
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}

1.2 必需与可选参数

在 FastAPI 中,查询参数可以是必需的或可选的。如果参数没有默认值,则它是必需的;如果有默认值,则是可选的。

1
2
3
@app.get("/users/")
async def read_users(user_id: int, is_active: bool = True):
return {"user_id": user_id, "is_active": is_active}

示例请求

  • 必需参数:/users/?user_id=123{"user_id": 123, "is_active": True}
  • 可选参数:/users/?user_id=123&is_active=False{"user_id": 123, "is_active": False}

1.3 默认值设置

通过为查询参数设置默认值,可以简化 API 的使用。

1
2
3
@app.get("/products/")
async def read_products(page: int = 1, per_page: int = 20):
return {"page": page, "per_page": per_page}

示例请求

  • 默认值:/products/{"page": 1, "per_page": 20}
  • 自定义值:/products/?page=2&per_page=50{"page": 2, "per_page": 50}

1.4 常见错误与解决方案

错误:422 Validation Error
原因:查询参数类型转换失败或校验不通过
解决方案:检查查询参数的类型定义和校验规则。


第二章:多参数处理

2.1 多个查询参数

FastAPI 支持在同一个接口中处理多个查询参数。

1
2
3
@app.get("/search/")
async def search_items(q: str, skip: int = 0, limit: int = 10):
return {"q": q, "skip": skip, "limit": limit}

示例请求

  • 多参数:/search/?q=apple&skip=10&limit=20{"q": "apple", "skip": 10, "limit": 20}

2.2 列表类型参数

通过使用 List 类型,可以处理多个相同类型的查询参数。

1
2
3
4
5
6
from typing import List


@app.get("/products/")
async def read_products(categories: List[str] = Query(...)):
return {"categories": categories}

示例请求

  • 列表参数:/products/?categories=electronics&categories=furniture{"categories": ["electronics", "furniture"]}

2.3 复杂参数校验

结合 Pydantic 的 FieldQuery,可以对查询参数进行复杂的校验。

1
2
3
4
5
6
from pydantic import Field


@app.get("/orders/")
async def read_orders(order_id: int = Query(..., gt=0), status: str = Field(..., regex=r"^(pending|completed)$")):
return {"order_id": order_id, "status": status}

示例请求

  • 合法:/orders/?order_id=123&status=pending{"order_id": 123, "status": "pending"}
  • 非法:/orders/?order_id=0&status=invalid → 422 错误

2.4 常见错误与解决方案

错误:422 Validation Error
原因:查询参数类型转换失败或校验不通过
解决方案:检查查询参数的类型定义和校验规则。


第三章:高级用法与最佳实践

3.1 参数别名

通过 Queryalias 参数,可以为查询参数设置别名。

1
2
3
@app.get("/users/")
async def read_users(user_id: int = Query(..., alias="id")):
return {"user_id": user_id}

示例请求

  • 别名:/users/?id=123{"user_id": 123}

3.2 参数描述与文档

通过 Querydescription 参数,可以为查询参数添加描述信息,这些信息将显示在 API 文档中。

1
2
3
@app.get("/products/")
async def read_products(category: str = Query(..., description="Filter products by category")):
return {"category": category}

示例请求

  • 描述:/products/?category=electronics{"category": "electronics"}

3.3 参数弃用

通过 Querydeprecated 参数,可以标记查询参数为弃用。

1
2
3
@app.get("/items/")
async def read_items(old_param: str = Query(None, deprecated=True)):
return {"old_param": old_param}

示例请求

  • 弃用参数:/items/?old_param=value{"old_param": "value"}

3.4 常见错误与解决方案

错误:422 Validation Error
原因:查询参数类型转换失败或校验不通过
解决方案:检查查询参数的类型定义和校验规则。


课后测验

测验 1:必需与可选参数

问题:如何定义一个必需查询参数和一个可选查询参数?
答案

1
2
3
@app.get("/items/")
async def read_items(required_param: int, optional_param: str = "default"):
return {"required_param": required_param, "optional_param": optional_param}

测验 2:列表类型参数

问题:如何处理多个相同类型的查询参数?
答案

1
2
3
4
5
6
from typing import List


@app.get("/products/")
async def read_products(categories: List[str] = Query(...)):
return {"categories": categories}

错误代码应急手册

错误代码典型触发场景解决方案
422类型转换失败/正则不匹配检查参数定义的校验规则
404查询参数格式正确但资源不存在验证业务逻辑中的数据存在性
500未捕获的参数处理异常添加 try/except 包裹敏感操作
400自定义校验规则触发拒绝检查验证器的逻辑条件

常见问题解答

Q:查询参数能否使用枚举类型?
A:可以,使用 Enum 类实现:

1
2
3
4
5
6
7
8
9
10
11
from enum import Enum


class Status(str, Enum):
ACTIVE = "active"
INACTIVE = "inactive"


@app.get("/users/")
async def get_users(status: Status):
return {"status": status}

Q:如何处理带斜杠的查询参数?
A:使用 Queryalias 参数或 URL 编码:

1
2
3
@app.get("/files/")
async def read_files(path: str = Query(..., alias="file-path")):
return {"path": path}

通过本文的详细讲解和实战项目,您已掌握 FastAPI 查询参数的核心知识。现在可以通过以下命令测试您的学习成果:

1
curl -X GET "http://localhost:8000/items/?skip=0&limit=10"

余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长,阅读完整的文章:

往期文章归档: