Wednesday, 1 December 2021

FastAPI: Send multiple body payloads

FastAPI allows you to declare multiple body payloads.

 

Example

@app.post("/emps")
def createEmployee(emp: Employee, address: Address)

 In the above example, FastAPI will notice that there are more than one body parameters in the function. So, it will then use the parameter names as keys (field names) in the body, and expect a body like below. 

{
  "emp": {
    "name": "PTR",
    "age": 33
  },
  "address": {
    "street": "CH street",
    "city": "Delhi"
  }
}

 

FastAPI will do the automatic conversion from the request, so that the parameter ‘emp’ receives it's specific content and the same for ‘address’.

 

Find the below working application.

 

multipleBodyParams.py

from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "address": {
            "street" : "Chowdeswari",
            "city" : "Bangalore"
        }
    }
}

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

class Address(BaseModel):
    street: str
    city: str

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee, address: Address):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)
    emps[newId]['address'] = dict(address)

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age'],
        "address" : emps[newId]['address']
        }

 

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

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

 

Open the url ‘http://127.0.0.1:8000/docs’ in browser and experiment with ‘POST /emps’ api.

 


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment