Thursday 11 November 2021

FastAPI: Required and optional query parameters

How to specify a required query parameter?

Declare the query parameter without any default value.

 

How to specify a query parameter optional?

Set the default value of the query parameter to None.

@app.get("/emps")
def emps( sortBy: str, pageNum : int = 1, pageSize : Optional[int] = None):
    return {'received' : {'sortBy' : sortBy, 'pageNum' : pageNum, 'pageSize': pageSize}}

 

In the above example,

a.   sortBy is a mandatory parameter

b.   pageNum is an int with default value 1.

c.    pageSize is optional parameter.





defaultAndRequiredParams.py

from fastapi import FastAPI, Path
from typing import Optional

app = FastAPI()

@app.get("/")
def home():
    return {'name' : 'Hello World app', 'version': '2.0.0'}

@app.get("/emps")
def emps( sortBy: str, pageNum : int = 1, pageSize : Optional[int] = None):
    return {'received' : {'sortBy' : sortBy, 'pageNum' : pageNum, 'pageSize': pageSize}}

  Open terminal and execute the command ‘uvicorn defaultAndRequiredParams:app --reload’ to run the application.

 

$uvicorn defaultAndRequiredParams:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [42779] using statreload
INFO:     Started server process [42781]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:59676 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:59676 - "GET /openapi.json HTTP/1.1" 200 OK

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment