Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 810
Fefe Avatar asked Sep 10 '25 18:09

Fefe


1 Answers

You can either use the Field function with min_length and max_length:

from pydantic import Field

class Foo(BaseModel):
    fixed_size_list_parameter: list[float] = Field(..., min_length=4, max_length=4)

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

from pydantic import conlist

class Foo(BaseModel):
    # these were named min_length and max_length in Pydantic v1.10
    fixed_size_list_parameter: conlist(float, min_length=4, max_length=4)

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

like image 137
MatsLindh Avatar answered Sep 15 '25 03:09

MatsLindh