Friday, 29 October 2021

FastAPI: Add numeric validations on path parameter

You can specify numeric validations on Path parameters. You can supply attributes gt, ge, lt and le to perform numeric checks.

 

a.   gt: greater than

b.   ge: greater than or equal

c.    lt: less than

d.   le: less than or equal

 

Example

@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))

 

main.py

from fastapi import FastAPI, Path

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))

 

Run main.py 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 [78097] using statreload
INFO:     Started server process [78099]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://127.0.0.1:8000/docs’ in browser, expand the REST api /emps/by-id/{empId} and try with employee id <= 0 or > 2, you will see validation error messages.

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment