Monday 6 December 2021

FastAPI: Define request sample payload

You can declare an example for a Pydantic model using Config and schema_extra.

 

Let’s it with an example.

class Employee(BaseModel):
    name: str 
    age : int

    class Config:
        schema_extra = {
            "example": {
                "name" : "Krishna",
                "age": 32
            }
        }

 

Find the below working application.

 

requestSamplePayload.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 
    age : int

    class Config:
        schema_extra = {
            "example": {
                "name" : "Krishna",
                "age": 32
            }
        }

@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 requestSamplePayload:app --reload'.

$uvicorn requestSamplePayload:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [48725] using statreload
INFO:     Started server process [48727]
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 sample payload for this request.

 


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment