声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数。

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]

查询字符串是键值对的集合,这些键值对位于URL的 之后,以&分隔。

上面运行后访问的URL为: http:/127.0.0.1:8000/items/?skip=0&limit=10

访问结果为:

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

 

默认值

上面代码中 skip=0和 limit=10设定为默认值。

如果访问: http:127.0.0.1:8000/items/?skip=20skip=20为在URL中设定的值,这时limit=10,表示默认值为10.

 

可选参数

from fastapi import FastAPI

from typing import Optional

app = FastAPI()

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

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

 

查询参数类型转换

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

from typing import Optional
from fastapi import FastAPI

app = FastAIP()

@app.get("/items/{item_id}")
async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
    item = {"item_id": item_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

访问URL http://127.0.0.1:8000/items/foo?short=1的结果如下:

{
    "item_id":"foo"
}

访问URL http://127.0.0.1:8000/items/foo?short=True的结果如下:

{
    "item_id":"foo"
}

访问URL http://127.0.0.1:8000/items/foo?short=true的结果如下:

{
    "item_id":"foo"
}

访问URL http://127.0.0.1:8000/items/foo?short=false的结果如下:

{
    "item_id":"foo","description":"This is an amazing item that has a long description"
}

访问URL http://127.0.0.1:8000/items/foo?short=False  的结果如下:

{
    "item_id":"foo","description":"This is an amazing item that has a long description"
}

访问URL http://127.0.0.1:8000/items/foo的结果如下:

{
    "item_id":"foo","description":"This is an amazing item that has a long description"
}

 

多个路径参数和查询参数

FastAPI可以识别同时声明的多个路径参数和查询参数,而且声明查询参数的顺序并不重要。

from typing import Optional
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: Optional[str] = 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

 

必选查询参数

如果要把查询参数设置为必选,就不要声明默认值:

from fastapi import FastAPI

app = FastAPI()

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

这里的查询参数 needy的类型为 str的必选查询参数。

访问URL http://127.0.0.1:8000/items/foo-item时报错,报错信息如下:

{
    "detail": [
        {
            "loc": [
                "query",
                "needy"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

访问URL http://127.0.0.1:8000/items/foo-item?needy=soomneedy的结果如下:

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

 

当然,把一些参数定义为必选,另一些参数设置为默认值,再把其他参数定义为可选,这些操作都是可以的。

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


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

上面代码中参数分别是:

  • needy 为必选参数
  • skip为默认值参数,默认值为0
  • limit为可选参数
posted on 2022-04-27 20:18  司徒轩宇  阅读(256)  评论(0编辑  收藏  举报