Is it possible to impose the length for a list attribute of the request body with fastapi?

Viewed 2094

Is it possible to specify the length of a list in the schema of the request body (or response)? There is support for validating the length of a string passed in the url with the Query function but I see nothing for lists.. Possible use case would be sending list of floats of fixed size to feed to a ML model.

1 Answers

You can either use the Field function with min_items and max_items:

from pydantic import Field

class Foo(BaseModel):
    fixed_size_list_parameter: float = Field(..., min_items=4, max_items=4)

.. or you can use the conlist (constrained list) type from pydantic:

from pydantic import conlist

class Foo(BaseModel):
    fixed_size_list_parameter: conlist(float, min_items=4, max_items=4)

This limits the list to exactly four entries of the float type.

Related