Sunday 7 November 2021

FastAPI: make the query parameters optional

By setting the value to None, we can make the query parameters optional.

 

Example

@app.get("/emps/by-name")
def emByName(name: Optional[str] = None):
    if name == None:
        return {"message" : "no input provided"}
    for empId in emps:
        if emps[empId]["name"] == name:
            return emps[empId]
    return {"message" : "Not found"}

 

main.py

from fastapi import FastAPI, Path
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32
    },
    2 : {
        "name" : "Ram",
        "age": 33
    }
}

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

# Employees REST APIs
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    if(empId in emps):
        return emps[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

@app.get("/emps/by-name")
def emByName(name: Optional[str] = None):
    if name == None:
        return {"message" : "no input provided"}
    for empId in emps:
        if emps[empId]["name"] == name:
            return emps[empId]
    return {"message" : "Not found"}

Run the application by executing the command 'uvicorn main:app --reload'.

 

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

  Open the url ‘http://127.0.0.1:8000/docs’ in browser, and experiment with the api ‘/emps/by-name’.

 

 


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment