Ana içeriğe geç

Path Parametreleri ve Sayısal Doğrulamalar

🌐 Yapay Zekâ ve İnsanlar Tarafından Çeviri

Bu çeviri, insanlar tarafından yönlendirilen bir yapay zekâ ile oluşturuldu. 🤝

Orijinal anlamın yanlış anlaşılması ya da kulağa doğal gelmeme gibi hatalar içerebilir. 🤖

Yapay zekâyı daha iyi yönlendirmemize yardımcı olarak bu çeviriyi iyileştirebilirsiniz.

İngilizce sürüm

Query ile query parametreleri için daha fazla doğrulama ve metadata tanımlayabildiğiniz gibi, Path ile de path parametreleri için aynı tür doğrulama ve metadata tanımlayabilirsiniz.

Path'i İçe Aktarın

Önce fastapi içinden Path'i ve Annotated'ı içe aktarın:

from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")],
    q: Annotated[str | None, Query(alias="item-query")] = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants
from typing import Annotated, Union

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")],
    q: Annotated[Union[str, None], Query(alias="item-query")] = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: int = Path(title="The ID of the item to get"),
    q: str | None = Query(default=None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Tip

Prefer to use the Annotated version if possible.

from typing import Union

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: int = Path(title="The ID of the item to get"),
    q: Union[str, None] = Query(default=None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Bilgi

FastAPI, 0.95.0 sürümünde Annotated desteğini ekledi (ve bunu önermeye başladı).

Daha eski bir sürüm kullanıyorsanız, Annotated kullanmaya çalıştığınızda hata alırsınız.

Annotated kullanmadan önce mutlaka FastAPI sürümünü en az 0.95.1 olacak şekilde FastAPI sürümünü yükseltin.

Metadata Tanımlayın

Query için geçerli olan parametrelerin aynısını tanımlayabilirsiniz.

Örneğin, item_id path parametresi için bir title metadata değeri tanımlamak isterseniz şunu yazabilirsiniz:

from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")],
    q: Annotated[str | None, Query(alias="item-query")] = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants
from typing import Annotated, Union

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")],
    q: Annotated[Union[str, None], Query(alias="item-query")] = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: int = Path(title="The ID of the item to get"),
    q: str | None = Query(default=None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Tip

Prefer to use the Annotated version if possible.

from typing import Union

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: int = Path(title="The ID of the item to get"),
    q: Union[str, None] = Query(default=None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Not

Bir path parametresi her zaman zorunludur, çünkü path'in bir parçası olmak zorundadır. None ile tanımlasanız veya bir varsayılan değer verseniz bile bu hiçbir şeyi değiştirmez; yine her zaman zorunlu olur.

Parametreleri İhtiyacınıza Göre Sıralayın

İpucu

Annotated kullanıyorsanız, bu muhtemelen o kadar önemli ya da gerekli değildir.

Diyelim ki query parametresi q'yu zorunlu bir str olarak tanımlamak istiyorsunuz.

Ayrıca bu parametre için başka bir şey tanımlamanız gerekmiyor; dolayısıyla Query kullanmanıza da aslında gerek yok.

Ancak item_id path parametresi için yine de Path kullanmanız gerekiyor. Ve bir sebepten Annotated kullanmak istemiyorsunuz.

Python, "default" değeri olan bir parametreyi, "default" değeri olmayan bir parametreden önce yazarsanız şikayet eder.

Ama bunların sırasını değiştirebilir ve default değeri olmayan parametreyi (query parametresi q) en başa koyabilirsiniz.

Bu FastAPI için önemli değildir. FastAPI parametreleri isimlerine, tiplerine ve default tanımlarına (Query, Path, vb.) göre tespit eder; sırayla ilgilenmez.

Dolayısıyla fonksiyonunuzu şöyle tanımlayabilirsiniz:

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants
from typing import Annotated

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Ancak şunu unutmayın: Annotated kullanırsanız bu problem olmaz; çünkü Query() veya Path() için fonksiyon parametresi default değerlerini kullanmıyorsunuz.

from typing import Annotated

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: Annotated[int, Path(title="The ID of the item to get")]
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(q: str, item_id: int = Path(title="The ID of the item to get")):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Parametreleri İhtiyacınıza Göre Sıralayın: Küçük Hileler

İpucu

Annotated kullanıyorsanız, bu muhtemelen o kadar önemli ya da gerekli değildir.

İşte bazen işe yarayan küçük bir hile; ama çok sık ihtiyacınız olmayacak.

Şunları yapmak istiyorsanız:

  • q query parametresini Query kullanmadan ve herhangi bir default değer vermeden tanımlamak
  • item_id path parametresini Path kullanarak tanımlamak
  • bunları farklı bir sırada yazmak
  • Annotated kullanmamak

...Python bunun için küçük, özel bir sözdizimi sunar.

Fonksiyonun ilk parametresi olarak * geçin.

Python bu * ile bir şey yapmaz; ama bundan sonraki tüm parametrelerin keyword argument (anahtar-değer çiftleri) olarak çağrılması gerektiğini bilir; buna kwargs da denir. Default değerleri olmasa bile.

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants
from typing import Annotated

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Annotated ile Daha İyi

Şunu da unutmayın: Annotated kullanırsanız, fonksiyon parametresi default değerlerini kullanmadığınız için bu sorun ortaya çıkmaz ve muhtemelen * kullanmanız da gerekmez.

from typing import Annotated

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")], q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(*, item_id: int = Path(title="The ID of the item to get"), q: str):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Sayı Doğrulamaları: Büyük Eşit

Query ve Path (ve ileride göreceğiniz diğerleri) ile sayı kısıtları tanımlayabilirsiniz.

Burada ge=1 ile, item_id değerinin 1'den "greater than or equal" olacak şekilde bir tam sayı olması gerekir.

from typing import Annotated

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get", ge=1)], q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *, item_id: int = Path(title="The ID of the item to get", ge=1), q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Sayı Doğrulamaları: Büyük ve Küçük Eşit

Aynısı şunlar için de geçerlidir:

  • gt: greater than
  • le: less than or equal
from typing import Annotated

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get", gt=0, le=1000)],
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(title="The ID of the item to get", gt=0, le=1000),
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Sayı Doğrulamaları: float Değerler, Büyük ve Küçük

Sayı doğrulamaları float değerler için de çalışır.

Burada gt tanımlayabilmek (sadece ge değil) önemli hale gelir. Çünkü örneğin bir değerin 0'dan büyük olmasını isteyebilirsiniz; 1'den küçük olsa bile.

Bu durumda 0.5 geçerli bir değer olur. Ancak 0.0 veya 0 geçerli olmaz.

Aynısı lt için de geçerlidir.

from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)],
    q: str,
    size: Annotated[float, Query(gt=0, lt=10.5)],
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    if size:
        results.update({"size": size})
    return results
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
    q: str,
    size: float = Query(gt=0, lt=10.5),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    if size:
        results.update({"size": size})
    return results

Özet

Query, Path (ve henüz görmedikleriniz) ile metadata ve string doğrulamalarını, Query Parametreleri ve String Doğrulamalar bölümündekiyle aynı şekilde tanımlayabilirsiniz.

Ayrıca sayısal doğrulamalar da tanımlayabilirsiniz:

  • gt: greater than
  • ge: greater than or equal
  • lt: less than
  • le: less than or equal

Bilgi

Query, Path ve ileride göreceğiniz diğer class'lar ortak bir Param class'ının alt class'larıdır.

Hepsi, gördüğünüz ek doğrulama ve metadata parametrelerini paylaşır.

Teknik Detaylar

Query, Path ve diğerlerini fastapi içinden import ettiğinizde, bunlar aslında birer fonksiyondur.

Çağrıldıklarında, aynı isme sahip class'ların instance'larını döndürürler.

Yani Query'yi import edersiniz; bu bir fonksiyondur. Onu çağırdığınızda, yine Query adlı bir class'ın instance'ını döndürür.

Bu fonksiyonlar (class'ları doğrudan kullanmak yerine) editörünüzün type'larıyla ilgili hata işaretlememesi için vardır.

Bu sayede, bu hataları yok saymak üzere özel ayarlar eklemeden normal editörünüzü ve coding araçlarınızı kullanabilirsiniz.