2022-02-24

Conditionnal call of a FastApi Model

I have a multilang FastApi connected to MongoDB. My document in MongoDB is duplicated in the two languages available and structured this way (simplified example):


{
  "_id": xxxxxxx,
  "en": { 
          "title": "Drinking Water Composition",
          "description": "Drinking water composition expressed in... with pesticides.",
          "category": "Water", 
          "tags": ["water","pesticides"] 
         },
  "fr": { 
          "title": "Composition de l'eau de boisson",
          "description": "Composition de l'eau de boisson exprimée en... présence de pesticides....",
          "category": "Eau", 
          "tags": ["eau","pesticides"] 
         },  
}

I therefore implemented two models DatasetFR and DatasetEN, each one make references with specific external Models (Enum) for category and tags in each lang .

class DatasetFR(BaseModel):
    title:str
    description: str
    category: CategoryFR
    tags: Optional[List[TagsFR]]

# same for DatasetEN chnaging the lang tag to EN 

In the routes definition I forced the language parameter to declare the corresponding Model and get the corresponding validation.


@router.post("?lang=fr", response_description="Add a dataset")
async def create_dataset(request:Request, dataset: DatasetFR = Body(...), lang:str="fr"):
    ...
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_dataset)

@router.post("?lang=en", response_description="Add a dataset")
async def create_dataset(request:Request, dataset: DatasetEN = Body(...), lang:str="en"):
    ...
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_dataset)

But this seems to be in contradiction with the DRY principle. So, I wonder here if someone knows an elegant solution to: - given the parameter lang, dynamically call the corresponding model.

Or if we can create a Parent Model Dataset that takes the lang argument and retrieve the child model Dataset.

This would incredibly ease building my API routes and the call of my models and mathematically divide by two the writing...



No comments:

Post a Comment