0
votes

I have an enum class for storing some categorical values like this.

class Fields(str, Enum):
    text   = "text"
    para   = "para"
    images = "images"

And there are pydantic models for each of these types. For example:

class imageModel(BaseModel):
    min_width       : int
    max_height      : int
    is_exact        : int
    is_proportional : int
    default_mode    : int
    default_quality : int

And I have a dict like this:

type_attrs = {
    "text": textModel,
    "para": ParaModel,
    "image": imageModel
}

I have a FastAPI route where the user needs to input the Field type name as string (taken as dropdown from fastapi docs) and supply the type attributes according to the type chosen. If the user selects type = "images", the corresponding pydantic model "ImageModel" would be provided for thr user to fill in and so on.

Is there any way the corresponding pydantic model can be produced after selecting the type name?

Thanks.

2

2 Answers

1
votes

You can use Union or List with your response_model

From the documentation:

You can declare a response to be the Union of two types, that means, that the response would be any of the two.

With Union

from typing import Union

@app.get("/my_path", response_model=Union[FirstModel, SecondModel])

With List

from typing import List

@app.get("/my_path", response_model=List[FirstModel, SecondModel])
1
votes

I don't think FastAPI can support this type of functionality. Basically what you are asking is for dynamic swagger model rendering based on the input from the Fields enum. This would require a hook into the swagger page I believe. Basically the entire swagger page is built statically at runtime of the api. I would suggest you break the Fields enum into separate paths on the same route.

class imageModel(BaseModel):
    min_width: int
    max_height: int
    is_exact: int
    is_proportional: int
    default_mode: int
    default_quality: int


@app.post("/image")
def image(image: imageModel):
    print(image)
    return None