深入解析 FastAPI 查询参数:配置、类型转换与灵活组合

深入解析 FastAPI 查询参数:配置、类型转换与灵活组合

本文全面解析了 FastAPI 查询参数的使用方法,包括配置默认值、设为可选或必选参数、类型转换以及组合使用等实用技巧。通过查询参数,开发者可以在路径操作函数中接收动态输入,灵活地构建 API 接口。文章详细说明了如何利用类型转换实现参数的自动解析和校验,同时展示了多个查询参数和路径参数组合使用的示例,为开发高效、灵活的 API 提供了可靠的指导。

示例使用 Python 版本为 Python 3.10.15

一 简介

路径操作函数会把非路径参数自动解释为查询参数。示例:

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{
    
    "item_name": "Foo"}, {
    
    "item_name": "Bar"}, {
    
    "item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

代码示例在 chapter03.py 中,运行如下命令:

$ uvicorn chapter03:app --reload

在线 SwaggerUI 文档,访问以下 URL :

http://127.0.0.1:8000/items/?skip=0&limit=10

查询参数为:

  • skip:值为 0
  • limit:值为 10

二 设置默认值

声明方法 async def read_item(skip: int = 0, limit: int = 10)skip=0limit=10 设定默认值。

访问 URL:

http://127.0.0.1:8000/items/

与访问以下地址相同:

http://127.0.0.1:8000/items/?skip=0&limit=10

但如果访问:

http://127.0.0.1:8000/items/?skip=20

查询参数的值就是:

  • skip=20:在 URL 中设定的值
  • limit=10:使用默认值

三 可选参数

默认值设为 None 时,查询参数为可选参数。

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None):
    if q:
        return {
    
    "item_id": item_id, "q": q}
    return {
    
    "item_id": item_id}

本例中,查询参数 q 是可选的,默认值为 None

四 查询参数类型转换

参数还可以声明为 bool 类型,FastAPI 会自动转换参数类型:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items02/{item_id}")
async def read_item(item_id: str, q: str | None = None, short: bool = False):
    item = {
    
    "item_id": item_id}
    # 如果 q 有值就更新
    if q:
        item.update({
    
    "q": q})
    if not short:
        item.update(
            {
    
    "description": "This is an amazing item that has a long description"}
        )
    return item

本例中,访问:

http://127.0.0.1:8000/items02/foo?short=1
http://127.0.0.1:8000/items02/foo?short=True
http://127.0.0.1:8000/items02/foo?short=true
http://127.0.0.1:8000/items02/foo?short=on
http://127.0.0.1:8000/items02/foo?short=yes

函数接收的 short 布尔类型参数都会自动转换。

五 多个路径和查询参数

from fastapi import FastAPI

app = FastAPI()


@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
    user_id: int, item_id: str, q: str | None = None, short: bool = False
):
    item = {"item_id": item_id, "owner_id": user_id}
    if q:
        item.update({"q": q})
    if not short:
        item.update(
            {"description": "This is an amazing item that has a long description"}
        )
    return item

FastAPI 通过参数名进行检测,声明的查询参数的顺序并不重要。

六 必选查询参数

如果要把查询参数设置为必选,就不要设置默认值。在参数声明中设置默认值则该参数就不是必选参数。把参数设为可选,但又不想指定参数的默认值,则要把值设为 None

from fastapi import FastAPI

app = FastAPI()


@app.get("/items03/{item_id}")
async def read_user_item(item_id: str, needy: str):
    item = {
    
    "item_id": item_id, "needy": needy}
    return item

这里的查询参数 needy 是必选参数。访问 URL :

http://127.0.0.1:8000/items03/foo-item?needy=sooooneedy

响应返回 JSON:

{
    
    
    "item_id": "foo-item",
    "needy": "sooooneedy"
}

七 组合参数

from fastapi import FastAPI

app = FastAPI()


@app.get("/items04/{item_id}")
async def read_user_item(
        item_id: str, needy: str, skip: int = 0, limit: int | None = None
):
    item = {
    
    "item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

本例中有 3 个查询参数和 1 个路径参数:

  • needy,必选的 str 类型参数
  • skip,默认值为 0int 类型参数
  • limit,可选的 int 类型参数
  • item_id,必选的 str 类型参数

八 完整代码示例

from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{
    
    "item_name": "Foo"}, {
    
    "item_name": "Bar"}, {
    
    "item_name": "Baz"}]


@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip: skip + limit]


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = None):
    if q:
        return {
    
    "item_id": item_id, "q": q}
    return {
    
    "item_id": item_id}


@app.get("/items02/{item_id}")
async def read_item(item_id: str, q: str | None = None, short: bool = False):
    item = {
    
    "item_id": item_id}
    # 如果 q 有值就更新
    if q:
        item.update({
    
    "q": q})
    if not short:
        item.update(
            {
    
    "description": "This is an amazing item that has a long description"}
        )
    return item


@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
        user_id: int, item_id: str, q: str | None = None, short: bool = False
):
    item = {
    
    "item_id": item_id, "owner_id": user_id}
    if q:
        item.update({
    
    "q": q})
    if not short:
        item.update(
            {
    
    "description": "This is an amazing item that has a long description"}
        )
    return item


@app.get("/items03/{item_id}")
async def read_user_item(item_id: str, needy: str):
    item = {
    
    "item_id": item_id, "needy": needy}
    return item


@app.get("/items04/{item_id}")
async def read_user_item(
        item_id: str, needy: str, skip: int = 0, limit: int | None = None
):
    item = {
    
    "item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

九 源码地址

详情见:GitHub FastApiProj

引用: FastAPI 文档

猜你喜欢

转载自blog.csdn.net/u014394049/article/details/143438051