Ana içeriğe geç

Sorgu Parametreleri

🌐 Translation by AI and humans

This translation was made by AI guided by humans. 🤝

It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖

You can improve this translation by helping us guide the AI LLM better.

English version

Fonksiyonda path parametrelerinin parçası olmayan diğer parametreleri tanımladığınızda, bunlar otomatik olarak "query" parametreleri olarak yorumlanır.

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]

Query, bir URL'de ? işaretinden sonra gelen ve & karakterleriyle ayrılan anahtar-değer çiftlerinin kümesidir.

Örneğin, şu URL'de:

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

...query parametreleri şunlardır:

  • skip: değeri 0
  • limit: değeri 10

URL'nin bir parçası oldukları için "doğal olarak" string'tirler.

Ancak, bunları Python tipleriyle (yukarıdaki örnekte int olarak) tanımladığınızda, o tipe dönüştürülürler ve o tipe göre doğrulanırlar.

Path parametreleri için geçerli olan aynı süreç query parametreleri için de geçerlidir:

  • Editör desteği (tabii ki)
  • Veri "parsing"
  • Veri doğrulama
  • Otomatik dokümantasyon

Varsayılanlar

Query parametreleri path'in sabit bir parçası olmadığından, opsiyonel olabilir ve varsayılan değerlere sahip olabilir.

Yukarıdaki örnekte varsayılan değerleri skip=0 ve limit=10'dur.

Yani şu URL'ye gitmek:

http://127.0.0.1:8000/items/

şuraya gitmekle aynı olur:

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

Ancak örneğin şuraya giderseniz:

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

Fonksiyonunuzdaki parametre değerleri şöyle olacaktır:

  • skip=20: çünkü URL'de siz ayarladınız
  • limit=10: çünkü varsayılan değer oydu

İsteğe bağlı parametreler

Aynı şekilde, varsayılan değerlerini None yaparak isteğe bağlı query parametreleri tanımlayabilirsiniz:

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}
🤓 Other versions and variants
from typing import Union

from fastapi import FastAPI

app = FastAPI()


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

Bu durumda, fonksiyon parametresi q isteğe bağlı olur ve varsayılan olarak None olur.

Ek bilgi

Ayrıca, FastAPI path parametresi olan item_id'nin bir path parametresi olduğunu ve q'nun path olmadığını fark edecek kadar akıllıdır; dolayısıyla bu bir query parametresidir.

Sorgu parametresi tip dönüşümü

bool tipleri de tanımlayabilirsiniz, ve bunlar dönüştürülür:

from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: str, q: str | None = 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
🤓 Other versions and variants
from typing import Union

from fastapi import FastAPI

app = FastAPI()


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

Bu durumda, şuraya giderseniz:

http://127.0.0.1:8000/items/foo?short=1

veya

http://127.0.0.1:8000/items/foo?short=True

veya

http://127.0.0.1:8000/items/foo?short=true

veya

http://127.0.0.1:8000/items/foo?short=on

veya

http://127.0.0.1:8000/items/foo?short=yes

veya başka herhangi bir büyük/küçük harf varyasyonunda (tamamı büyük, ilk harf büyük, vb.), fonksiyonunuz short parametresini bool değeri True olarak görecektir. Aksi halde False olarak görür.

Çoklu path ve query parametreleri

Aynı anda birden fazla path parametresi ve query parametresi tanımlayabilirsiniz; FastAPI hangisinin hangisi olduğunu bilir.

Ayrıca bunları belirli bir sırayla tanımlamanız gerekmez.

İsme göre tespit edilirler:

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
🤓 Other versions and variants
from typing import Union

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: Union[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

Zorunlu query parametreleri

Path olmayan parametreler (şimdilik sadece query parametrelerini gördük) için varsayılan değer tanımladığınızda, bu parametre zorunlu olmaz.

Belirli bir değer eklemek istemiyor ama sadece opsiyonel olmasını istiyorsanız, varsayılanı None olarak ayarlayın.

Ancak bir query parametresini zorunlu yapmak istediğinizde, herhangi bir varsayılan değer tanımlamamanız yeterlidir:

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

Burada query parametresi needy, str tipinde zorunlu bir query parametresidir.

Tarayıcınızda şöyle bir URL açarsanız:

http://127.0.0.1:8000/items/foo-item

...zorunlu needy parametresini eklemeden, şuna benzer bir hata görürsünüz:

{
  "detail": [
    {
      "type": "missing",
      "loc": [
        "query",
        "needy"
      ],
      "msg": "Field required",
      "input": null
    }
  ]
}

needy zorunlu bir parametre olduğundan, URL'de ayarlamanız gerekir:

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

...bu çalışır:

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

Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli, bazılarını da tamamen isteğe bağlı olarak tanımlayabilirsiniz:

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: int | None = None
):
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item
🤓 Other versions and variants
from typing import Union

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: Union[int, None] = None
):
    item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
    return item

Bu durumda, 3 tane query parametresi vardır:

  • needy, zorunlu bir str.
  • skip, varsayılan değeri 0 olan bir int.
  • limit, isteğe bağlı bir int.

İpucu

Path Parametreleri ile aynı şekilde Enum'ları da kullanabilirsiniz.