Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamical body in FastApi using Pydantic

I would like to have a dynamical mandatory body on FastApi.

I explain :

from fastapi import FastAPI, Body
from pydantic import BaseModel

app = FastAPI()

class Parameters(BaseModel):
    platform: str
    country: str

@app.put("/myroute")
async def provision_instance(*, parameters: Parameters = Body(...)):
    do_something

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=80)

Here, my body is manually defined in the Parameters class with two attributes, platform and country. In the future, these attributes will come from a configuration file and there will be more than two attributes. So I will need to create them automatically on the fly.

For example, in the configuration file, I could have :

---
parameters:
  application:
    description: "Name of the application"
    type: string
  platform:
    description: "Name of the platform"
    type: string
  country:
    description: "Name of the country"
    type: string

How could I have in this context a variable number of parameters required in the body ? Should I find a way to give to my Parameters class a variable number of attributes ?

like image 466
Nico Avatar asked Jan 27 '26 11:01

Nico


1 Answers

Pydantic models can be built dynamically as described in this section of the documentation. You would still have to implement a function that will read your yaml file and build the Pydantic model from it.


Now consider a few Pydantic models in a python file ; aren't this equivalent to having a yaml file describing models ?


If you came up with with this plan of dynamically building Pydantic models because you will have multiple shape of data coming in, you might also explore using typing.Union for defining your endpoint :


class Parameters1(BaseModel):
    platform: str
    country: str


class Parameters2(BaseModel):
    application: str
    country: str


@app.put("/myroute")
async def provision_instance(*, parameters: Union[Parameters1, Parameters2] = Body(...)):
    if isinstance(parameters, Parameters1):
        pass  # TODO
    elif isinstance(parameters, Parameters2):
        pass  # TODO

like image 68
Thomasleveil Avatar answered Jan 29 '26 02:01

Thomasleveil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!