Saturday 29 January 2022

FastAPI: Declare response model with default values

FastAPI allows you to declare a response model with default values.

 

Example

class Employee(BaseModel):
    name: str
    age: int
    country: str = 'India'
    tax: float = 30.5

 

In the above example, country field has a default value 'India' and tax has default value 30.5.

Let’s see it with an example.

responseModelDefaultValues.py
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from enum import Enum

app = FastAPI()

class CountryEnum(str, Enum):
    India = "India"
    China = "China"
    Russia = "Russia"

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str = 'India'
    tax: float = 30.5

emp1 = Employee(name= "Krishna", age = 32, country = "India", tax = 20)
emp2 = Employee(name= "Ram", age = 42, country = "China", tax = 35)
emp3 = Employee(name= "Sailu", age = 33)

employees = {1 : emp1, 2 : emp2, 3 : emp3}

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

 

Open terminal and execute the command ‘uvicorn responseModelDefaultValues:app –reload’.

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

 


 

As you observe above image, following details are returned for employee

with id 3.

{
  "name": "Sailu",
  "age": 33,
  "country": "India",
  "tax": 30.5
}

But Employee with id is set with values name and age, remaining properties are returned with default values.


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment