Thursday 18 November 2021

FastAPI: Add metadata and validations to query parameters

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

 

Adding metadata and validations

Using Query, we can add additional metadata and apply validations to the query parameter.

 

Example

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

In the above example, I added metadata ‘title’ and ‘description’ to the query parameter productId. Validations like min_length, max_length are applied to productId.

 

Adding default values to the query parameter

First parameter of Query serves the purpose of defining default valie. For example, if user do not provide any value to the query parameter ‘formatType’, then JSON is considered.

 

Mandatory query parameters

Approach 1: If validations and metadata are not required to the query parameter, just do not declare a default value.

param: str

 

Approach 2: If you need to add validations to the query parameter, use ... as the first argument.

param: str = Query(...)



For the above example,

a.   infoLevel and productId are mandatory parameters

b.   formatType is optional =, but provided with default value.

c.    noOfItems is optional and do not have a default value.

 

Adding regular expression

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

 

Example

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

Find the below working application.

 

queryParamValidations.py

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

app = FastAPI()

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

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

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

$uvicorn queryParamValidations:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [54341] using statreload
INFO:     Started server process [54343]
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