Friday 26 November 2021

FastAPI: specify alias name to a query parameter

Using ‘alias’ argument of Query function, you can specify an alias name to the query parameter.

 

Example

@app.get("/emps")
def empsInfo(
    ids : List[int] = Query(
        [2, 3], 
        alias='emp-id', 
        description="Please provide valid employee ids"
    )
)

 

Above snippet use the alias name ‘emp-id’ to populate the ids property.

 

aliasQueryParam.py

 

from fastapi import FastAPI, Query
from typing import List

app = FastAPI()

@app.get("/emps")
def empsInfo(
    ids : List[int] = Query(
        [2, 3], 
        alias='emp-id', 
        description="Please provide valid employee ids"
    )
):
    return {"ids" : ids}

Open terminal and execute the command ‘uvicorn aliasQueryParam:app --reload’.

 

$uvicorn aliasQueryParam:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [56302] using statreload
INFO:     Started server process [56306]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

 

Open the url ‘http://127.0.0.1:8000/docs’ in browser and experiment with swagger documentation.

 


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment