Using Body function, you can supply multiple examples of a request payload.
Example
@app.post("/emps")
def createEmployee(
emp: Employee = Body(
...,
examples = {
"example1" : {
"summary": "Example 1",
"description": "Example 1 payload",
"value" : {
"name" : "Krishna",
"age" : 31
}
},
"example2" : {
"summary": "Example 2",
"description": "Example 2 payload",
"value" : {
"name" : "Ram",
"age" : 42
}
}
}
)
)
Above snippet add two examples ‘exmaple1’ and ‘example2’ to the request.
Find the below working application.
addMultipleExamplesToReqPayload.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(
...,
examples = {
"example1" : {
"summary": "Example 1",
"description": "Example 1 payload",
"value" : {
"name" : "Krishna",
"age" : 31
}
},
"example2" : {
"summary": "Example 2",
"description": "Example 2 payload",
"value" : {
"name" : "Ram",
"age" : 42
}
}
}
)
):
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 addMultipleExamplesToReqPayload:app --reload’.
$ uvicorn addMultipleExamplesToReqPayload:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [41910] using statreload
INFO: Started server process [41913]
INFO: Waiting for application startup.
INFO: Application startup complete.
Open the url ‘http://localhost:8000/docs’ in browser and experiment with swagger documentation.
Previous Next Home
No comments:
Post a Comment