
查询参数的特点
/items?category=books&sort=ascfrom __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
参数:
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 参数应为有效整数
描述: 该路由展示了如何使用基本的查询参数,支持默认值和类型验证。

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
参数:
GET /query_2?a=9 返回错误,提示 a 参数应大于等于 10GET /query_2?a=101 返回错误,提示 a 参数应小于等于 100GET /query_2?a=99 返回 {"a":99,"b":"hello"}
描述: 该路由展示了如何使用带有约束条件的查询参数,确保输入值在特定范围内

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}
参数:
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}
描述: 该路由展示了如何结合路径参数和可选查询参数,处理默认值和动态计算

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}
参数:
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"}
描述: 该路由展示了如何使用路径参数和多个查询参数,处理条件逻辑以返回不同的响应

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}
参数:
示例请求:
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"}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。