Reputation: 37
I have a use case where I am accepting data of different datatypes - namely dict, boolean, string, int, list
- from the front end application to the FastAPI backedn using a pydantic model.
My question is how should I design my pydantic model so that it can accept any data type, which can later be used for manipulating the data and creating an API?
from pydantic import BaseModel
class Pino(BaseModel):
asset:str (The data is coming from the front end ((dict,boolean,string,int,list)) )
@app.post("/api/setAsset")
async def pino_kafka(item: Pino):
messages = {
"asset": item.asset
}
Upvotes: 1
Views: 2628
Reputation: 2133
Define a custom datatype:
from typing import Optional, Union
my_datatype = Union[dict,boolean,string,int,list]
In python 3.9 onwards, you don't need Union any-more:
my_datatype = dict | boolean | string | int | list
Then use it in your model:
class Pino(BaseModel):
asset: my_datatype
If you really want "any" datatype, just use "Any":
from typing import Any
class Pino(BaseModel):
asset: Any
In any case, I hardly find a use case for this, the whole point of using pydantic is imposing datatypes.
Upvotes: 3