Tips and Tricks

FastAPI

FastAPI - Using alias parameters to map fields from request to view arguments


FastAPI tip:

You can use aliases for field names to map fields from request to view arguments.

https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters

👇

from typing import Optional

from fastapi import FastAPI, Query, Path

app = FastAPI()


@app.get("/products/")
def search_products(query: Optional[str] = Query(None, alias="q")):
    products = [{"name": "Computer"}, {"name": "HDD"}]

    return {"results": [product for product in products if query in product["name"]]}


@app.get("/users/{id}/profile/")
def user_profile(user_id: int = Path(None, alias="id")):
    return {
        "id": user_id,
        "username": "johndoe"
    }