Wednesday, 17 November 2021

FastAPI: Add metadata and validations to path parameters

FastAPI allows you to declare additional information and validation for path and query parameters.

 

Adding metadata and validations

Using Path, we can add additional metadata to the path parameter.


@app.get("/products/{productId}/{noOfItems}/{infoLevel}/{formatType}")
def productInfo(
    infoLevel : str,
    productId: str = Path(
        ...,
        min_length = 4, 
        max_length=50,  
        title='Product id',
        description = "Enter valid product id"
        ), 
    noOfItems : int = Path(..., gt = 0, lt = 50, title='Number of items to return'),
    formatType : str = Path(..., min_length=2)
)

 

A path parameter is always required as it has to be part of the path.So, you should declare it with ... to mark it as required.

 

In the above example, I added title and description to the path parameter ‘productId’. I added validations to the productid by passing min_length and max_legth arguments to the path function. Similarly I added numeric validations (gt (>), lt (<)) to the path parameter noOfItems.

 

Add regular expression to a path parameter

Path function takes a 'regex' argument and validate the received path parameter against this regular expression.

 

Example

 

@app.get("/products/by-email/{email}")
def productsbyEmail(
    email: str = Path(..., max_length=50,  title='Valid email id', regex='[^@]+@[^@]+\.[^@]+')
):

 

Find the below working application.

 

pathParamValidations.py

 

from fastapi import FastAPI, Path
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

@app.get("/products/{productId}/{noOfItems}/{infoLevel}/{formatType}")
def productInfo(
    infoLevel : str,
    productId: str = Path(
        ...,
        min_length = 4, 
        max_length=50,  
        title='Product id',
        description = "Enter valid product id"
        ), 
    noOfItems : int = Path(..., gt = 0, lt = 50, title='Number of items to return'),
    formatType : str = Path(..., min_length=2)
):
    return {"productId" : productId, "noOfItems" : noOfItems, 'infoLevel' : infoLevel, 'formatType' : formatType}

@app.get("/products/by-email/{email}")
def productsbyEmail(
    email: str = Path(..., max_length=50,  title='Valid email id', regex='[^@]+@[^@]+\.[^@]+')
):
    return {"email" : email}

 

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

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

 

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

 


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment