How to specify one or more items from base model are present in the request body

Viewed 31

I have a FastApi application that has the following base model:

class Mint(BaseModel):
    investigation: Union[Investigation, None] = None
    dataset: Union[List[Dataset], None] = None
    datafile: Union[List[Datafile], None] = None

So the Request takes one investigation or one or more datasets or datafiles. How can I change it so one of these HAS to be included in the request body but none of them are madatory?

For example, the body can contain:

  • 1 Investigation and 2 datasets
  • 1 Investigation
  • 2 datasets
  • 4 datafiles

thanks

1 Answers

I solved this using the @root_validator tag

@root_validator()
    def check_contents(cls, values):
        if (values.get('investigation') is None) and \
                (values.get('dataset') is None) and \
                (values.get('datafile') is None):
            raise ValueError('either an investigation or a dataset or a datafile is required')
        return values
Related