Using Body function, you can add sample data to the request payload.
Example
@app.post("/emps")
def createEmployee(
emp: Employee = Body(
...,
example = {"name" : "Krishna", "age": 31}
)
)
Find the below working application.
requestSamplePayloadUsingBody.py
from fastapi import FastAPI, Body
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
# employees information
emps = {
1 : {
"name" : "Krishna",
"age": 32
}
}
class Employee(BaseModel):
name: str
age : int
@app.get("/emps")
def allEmployees():
return emps
@app.post("/emps")
def createEmployee(
emp: Employee = Body(
...,
example = {"name" : "Krishna", "age": 31}
)
):
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 requestSamplePayloadUsingBody:app --reload’.
$ uvicorn requestSamplePayloadUsingBody:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [40047] using statreload
INFO: Started server process [40050]
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.
No comments:
Post a Comment