Tuesday, 7 December 2021

FastAPI: Specify sample payload using Field

When using Field() with Pydantic models, you can also declare extra info for the JSON Schema by passing any other arbitrary arguments to the function.

 

Example

class Employee(BaseModel):
    name: str = Field(..., example = "Krishna")
    age : int = Field(..., example = 31)

 

Find the below working application.

 

requestSamplePayloadUsingField.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(..., example = "Krishna")
    age : int = Field(..., example = 31)

@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 requestSamplePayloadUsingField:app --reload’.

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

 

Open the url ‘http://localhost:8000/docs’ in browser and expand 'POST /emps' api, you will see the sample payload is documented.

 


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment