FastAPI后台开发基础(3):查询参数
什么是查询参数
查询参数的特点
- 位置:
查询参数位于 URL 的查询字符串部分,通常以 ? 开始,多个参数用 & 分隔。例如:
/items?category=books&sort=asc
- 可选性: 查询参数通常是可选的。如果客户端未提供某个查询参数,FastAPI 会将其视为 None,并可以在处理请求时进行相应的逻辑处理
- 类型: FastAPI 支持多种数据类型的查询参数,包括字符串、整数、布尔值等。你可以通过类型注解来指定查询参数的类型,FastAPI 会自动进行验证和转换
- 默认值: 可以为查询参数设置默认值。如果客户端未提供该参数,FastAPI 会使用默认值
- 文档生成: FastAPI 会自动生成 OpenAPI 文档,查询参数会在文档中清晰地列出,方便用户了解可用的参数及其类型
查询参数的使用
基本查询参数
代码语言:python代码运行次数:0运行复制from __future__ import annotations
from fastapi import FastAPI
app = FastAPI()
@app.get("/query")
async def async_root(a: int = 10, b: str = 'hello'):
"""
The query is the set of key-value pairs that go after the ? in a URL, separated by & characters.
curl -X 'GET' 'http://127.0.0.1:18081/query' -H 'accept: application/json'
{"a":10,"b":"hello"}
curl -X 'GET' 'http://127.0.0.1:18081/query?a=999&b=world' -H 'accept: application/json'
{"a":999,"b":"world"}
curl -X 'GET' 'http://127.0.0.1:18081/query?a=999' -H 'accept: application/json'
{"a":999,"b":"hello"}
curl -X 'GET' 'http://127.0.0.1:18081/query?a=world' -H 'accept: application/json'
{
"detail":[
{
"type":"int_parsing",
"loc":["query","a"],
"msg":"Input should be a valid integer, unable to parse string as an integer",
"input":"world"
}
]
}
"""
return {"a": a, 'b': b}
路由: /query
参数:
- a: 整数类型,默认值为 10
- b: 字符串类型,默认值为 'hello' 示例请求:
GET /query
返回{"a":10,"b":"hello"}
GET /query?a=999&b=world
返回{"a":999,"b":"world"}
GET /query?a=999
返回{"a":999,"b":"hello"}
GET /query?a=world
返回错误,提示 a 参数应为有效整数 描述: 该路由展示了如何使用基本的查询参数,支持默认值和类型验证。 基本查询参数
带有约束的查询参数
代码语言:python代码运行次数:0运行复制from __future__ import annotations
from fastapi import FastAPI
from pydantic import conint
app = FastAPI()
@app.get("/query_2")
async def async_root_2(a: conint(ge = 10, le = 100) = 10, b: str = 'hello'):
"""
curl -X 'GET' 'http://127.0.0.1:18081/query_2?a=9' -H 'accept: application/json'
{"detail":[{"type":"greater_than_equal","loc":["query","a"],"msg":"Input should be greater than or equal to 10","input":"9","ctx":{"ge":10}}]}
curl -X 'GET' 'http://127.0.0.1:18081/query_2?a=101' -H 'accept: application/json'
{"detail":[{"type":"less_than_equal","loc":["query","a"],"msg":"Input should be less than or equal to 100","input":"101","ctx":{"le":100}}]}
curl -X 'GET' 'http://127.0.0.1:18081/query_2?a=99' -H 'accept: application/json'
{"a":99,"b":"hello"}
"""
return {"a": a, 'b': b}
路由: /query_2
参数:
- a: 整数类型,必须在 10 到 100 之间(包含边界),默认值为 10
- b: 字符串类型,默认值为 'hello' 示例请求:
GET /query_2?a=9
返回错误,提示 a 参数应大于等于 10GET /query_2?a=101
返回错误,提示 a 参数应小于等于 100GET /query_2?a=99
返回{"a":99,"b":"hello"}
描述: 该路由展示了如何使用带有约束条件的查询参数,确保输入值在特定范围内 带有约束的查询参数
可选查询参数与路径参数
代码语言:python代码运行次数:0运行复制from __future__ import annotations
from fastapi import FastAPI
from pydantic import conint
app = FastAPI()
@app.get("/query_3/{item_id}")
async def async_root_3(item_id: str, offset: int | None = None, limit: int = 10):
"""
offset为可选参数,如果不传,则默认为0
limit为可选参数,如果不传,则默认为10
curl -X 'GET' 'http://127.0.0.1:18081/query_3/my_item?limit=99' -H 'accept: application/json'
{"item_id":"my_item","limit":99,"message":"no offset is not set, default to 0"}
curl -X 'GET' 'http://127.0.0.1:18081/query_3/my_item' -H 'accept: application/json'
{"item_id":"my_item","offset":0,"limit":10,"fake_total_count":10}
curl -X 'GET' 'http://127.0.0.1:18081/query_3/my_item?offset=199' -H 'accept: application/json'
{"item_id":"my_item","offset":199,"limit":10,"fake_total_count":2000}%
"""
if offset is None:
return {"item_id": item_id, "limit": limit, 'message': 'no offset is not set, default to 0'}
else:
return {"item_id": item_id, "offset": offset, "limit": limit, 'fake_total_count': limit * (offset + 1)}
路由: /query_3/{item_id}
参数:
- item_id: 路径参数,必需
- offset: 整数类型,可选,默认值为 0
- limit: 整数类型,可选,默认值为 10 示例请求:
GET /query_3/my_item?limit=99
返回{"item_id":"my_item","limit":99,"message":"no offset is not set, default to 0"}
GET /query_3/my_item
返回{"item_id":"my_item","offset":0,"limit":10,"fake_total_count":10}
GET /query_3/my_item?offset=199
返回{"item_id":"my_item","offset":199,"limit":10,"fake_total_count":2000}
描述: 该路由展示了如何结合路径参数和可选查询参数,处理默认值和动态计算 可选查询参数与路径参数
多个路径参数与多个查询参数
代码语言:python代码运行次数:0运行复制from __future__ import annotations
from fastapi import FastAPI
from pydantic import conint
app = FastAPI()
@app.get("/query_4/{user_id}/item/{item_id}")
async def async_root_4(user_id: int, item_id: str, q: str | None = None, show_detail: bool = False):
"""
路径参数通常是必需的,不能直接设置为可选
传 show_detail并设置为 False,不传 q 参数
curl -X 'GET' 'http://127.0.0.1:18081/query_4/1234/item/test_id1?show_detail=False' -H 'accept: application/json'
{"user_id":1234,"item_id":"test_id1"}
传 show_detail 并设置为 False,传 q 参数
curl -X 'GET' 'http://127.0.0.1:18081/query_4/1234/item/test_id1?show_detail=False&q=hello,world' -H 'accept: application/json'
{"user_id":1234,"item_id":"test_id1","q":"hello,world"}
传 show_detail 并设置为 True,传 q 参数
curl -X 'GET' 'http://127.0.0.1:18081/query_4/1234/item/test_id1?show_detail=True&q=hello,world' -H 'accept: application/json'
{"user_id":1234,"item_id":"test_id1","detail":"this is a detailed description for user:1234-test_id1","q":"hello,world"}
"""
ret = {'user_id': user_id, 'item_id': item_id}
if show_detail:
ret.update({'detail': f'this is a detailed description for user:{user_id}-{item_id}'})
if q is not None:
ret.update({'q': q})
return ret
路由: /query_4/{user_id}/item/{item_id}
参数:
- user_id: 路径参数,必需
- item_id: 路径参数,必需
- q: 字符串类型,可选
- show_detail: 布尔类型,默认值为 False 示例请求:
GET /query_4/1234/item/test_id1?show_detail=False
返回{"user_id":1234,"item_id":"test_id1"}
GET /query_4/1234/item/test_id1?show_detail=False&q=hello,world
返回{"user_id":1234,"item_id":"test_id1","q":"hello,world"}
GET /query_4/1234/item/test_id1?show_detail=True&q=hello,world
返回{"user_id":1234,"item_id":"test_id1","detail":"this is a detailed description for user:1234-test_id1","q":"hello,world"}
描述: 该路由展示了如何使用路径参数和多个查询参数,处理条件逻辑以返回不同的响应 多个路径参数与多个查询参数
必需的查询参数与可选查询参数
代码语言:python代码运行次数:0运行复制from __future__ import annotations
from fastapi import FastAPI
from pydantic import conint
app = FastAPI()
@app.get("/query_5/item/{item_id}")
async def async_root_5(item_id: str, needy: str, optional_param: str | None = None):
"""
查询参数可选,也可不选,不选时,默认值为 None
curl -X 'GET' 'http://127.0.0.1:18081/query_5/item/my_item_id?needy=hello&optional_param=world' -H 'accept: application/json'
{"item_id":"my_item_id","needy":"hello","optional_param":"world"}
curl -X 'GET' 'http://127.0.0.1:18081/query_5/item/my_item_id?needy=hello' -H 'accept: application/json'
{"item_id":"my_item_id","needy":"hello","optional_param":null}
curl -X 'GET' 'http://127.0.0.1:18081/query_5/item/my_item_id?optional_param=qqqq' -H 'accept: application/json'
{"detail":[{"type":"missing","loc":["query","needy"],"msg":"Field required","input":null}]}
如果查询参数的值带有特殊字符,则需要进行 url 编码
import urllib.parse
query = "hello & world?"
encoded_query = urllib.parse.quote(query)
print(encoded_query) # 输出: hello%20%26%20world%3F
使用编码后的参数发送请求并获取响应:
curl -X 'GET' 'http://127.0.0.1:18081/query_5/item/my_item_id?needy=hello%20%26%20world%3F&optional_param=qqqq' -H 'accept: application/json'
{"item_id":"my_item_id","needy":"hello & world?","optional_param":"qqqq"}
"""
return {"item_id": item_id, "needy": needy, "optional_param": optional_param}
路由: /query_5/item/{item_id}
参数:
- item_id: 路径参数,必需
- needy: 字符串类型,必需
- optional_param: 字符串类型,可选,默认值为 None
示例请求:
GET /query_5/item/my_item_id?needy=hello&optional_param=world
返回 1{"item_id":"my_item_id","needy":"hello","optional_param":"world"}
GET /query_5/item/my_item_id?needy=hello
返回{"item_id":"my_item_id","needy":"hello","optional_param":null}
GET /query_5/item/my_item_id?optional_param=qqqq
返回错误,提示 needy 参数是必需的
描述: 该路由展示了如何处理必需的查询参数和可选的查询参数,确保必需参数的存在
在查询参数的值中,如果包含特殊字符(如 &、?、= 等),需要进行 URL 编码。例如,值 hello & world?
应编码为 hello%20%26%20world%3F
,如:
GET /query_5/item/my_item_id?needy=hello%20%26%20world%3F&optional_param=qqqq
返回{"item_id":"my_item_id","needy":"hello & world?","optional_param":"qqqq"}
发布者:admin,转转请注明出处:http://www.yc00.com/web/1755065963a5234831.html
评论列表(0条)