Monday, 6 December 2021

FastAPI: Add validations to request payload

Using Pydantic's Field, you can add validations to the request payload. Let’s see it with an example.

 

Example

class Employee(BaseModel):
    name: str = Field(
        ..., 
        title="Employee name", 
        min_length = 3,
        max_length=30
    )
    
    age : int = Field(..., 
    gt = 18, 
    title="Employee age"
    )

In the above snippet, I added constraints to the fields ‘name’ and ‘age’. ‘name’

 

requestBodyValidations.py

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Optional

app = FastAPI()

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

class Employee(BaseModel):
    name: str = Field(
        ..., 
        title="Employee name", 
        min_length = 3,
        max_length=30
    )
    
    age : int = Field(..., 
    gt = 18, 
    title="Employee age"
    )

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age']
        }

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

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