1. 程式人生 > 其它 >FastAPI學習-3.get 請求 query params 查詢引數

FastAPI學習-3.get 請求 query params 查詢引數

前言

get 請求的引數在url 後面帶著,一般叫query params 查詢引數

查詢引數

宣告不屬於路徑引數的其他函式引數時,它們將被自動解釋為"查詢字串"引數

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

查詢引數skip:對應的值為 0, limit:對應的值為 10
由於它們是 URL 的一部分,因此它們的"原始值"是字串。
但是,當你為它們聲明瞭 Python 型別(在上面的示例中為 int)時,它們將轉換為該型別並針對該型別進行校驗。
應用於路徑引數的所有相同過程也適用於查詢引數:

  • (很明顯的)編輯器支援
  • 資料"解析"
  • 資料校驗
  • 自動生成文件

預設值

由於查詢引數不是路徑的固定部分,因此它們可以是可選的,並且可以有預設值。
在上面的示例中,它們具有 skip=0 和 limit=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 typing import Optional

from fastapi import FastAPI

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 型別,它們將被自動轉換:

from typing import Optional

from fastapi import FastAPI

app = FastAPI()


@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

這個例子中,如果你訪問:http://127.0.0.1:8000/items/foo?short=1 或者 short=True, short=true, short=on, short=yes
或任何其他的變體形式(大寫,首字母大寫等等),你的函式接收的 short 引數都會是布林值 True。對於值為 False 的情況也是一樣的。

多個路徑和查詢引數

你可以同時宣告多個路徑引數和查詢引數,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

必填項查詢引數

當你為非路徑引數聲明瞭預設值時(目前而言,我們所知道的僅有查詢引數),則該引數不是必需的。
如果你不想新增一個特定的值,而只是想使該引數成為可選的,則將預設值設定為 None。
但當你想讓一個查詢引數成為必需的,不宣告任何預設值就可以:

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
因為沒有新增必需的引數 needy,你將看到類似以下的錯誤:

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

由於 needy 是必需引數,因此你需要在 URL 中設定它的值:http://127.0.0.1:8000/items/foo-item?needy=sooooneedy

{
    "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

在這個例子中,有3個查詢引數:

  • needy,一個必需的 str 型別引數。
  • skip,一個預設值為 0 的 int 型別引數。
  • limit,一個可選的 int 型別引數。