Thursday, 2 December 2021

FastAPI: Singular values in request body

Usually, we can add extra data to an url using query and path parameters. In the same way, we can add extra singular values to the request body using Body() function.

 

Let’s see it with an example.

@app.post("/emps")
def createEmployee(emp: Employee, street: str = Body(...), city: str = Body(...))

 

Above snippet takes a payload like below.

{
  "emp": {
    "name": "Krishna",
    "age": 23
  },
  "street": "sss",
  "city": "Bangalore"
}

 

Find the below working application.

 

requestBodySingularValues.py 

from fastapi import FastAPI, Body
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

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

@app.post("/emps")
def createEmployee(emp: Employee, street: str = Body(...), city: str = Body(...)):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)

    address = {"street" : street, "city" : city}
    emps[newId]['address'] = address

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

Open terminal and execute the command ‘uvicorn requestBodySingularValues:app --reload’.

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

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



 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment