FastAPI 读取 GET 参数:使用 Query 参数获取请求数据
在 FastAPI 中,可以使用'Query'参数来读取 GET 请求中的参数。
以下是一个例子:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get('/items/')
async def read_items(q: str = Query(None)):
results = {'items': [{'item_id': 'Foo'}, {'item_id': 'Bar'}]}
if q:
results.update({'q': q})
return results
在上述例子中,我们定义了一个 GET 请求处理函数'read_items',其中'q'参数使用了'Query'函数来读取 GET 参数。如果没有提供'q'参数,它的默认值为'None'。
当我们发送一个 GET 请求到'/items/',可以通过在 URL 中添加查询参数来传递'q'参数,例如'/items/?q=test'。在处理函数中,我们可以使用'q'参数来获取查询参数的值。
原文地址: https://www.cveoy.top/t/topic/nDKw 著作权归作者所有。请勿转载和采集!