The Fool
The Fool

Reputation: 20517

enforce path contraints with fastapi

I am getting an error when using regex path contraint in fast api.

ValueError: On field "serial" the following field constraints are set but not enforced: regex. 
For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

The function signature looks like this.

@devices.get("/{serial}", response_model=Device)
async def get_serial(serial: int = Path(..., regex=r"(?:\d{18}|\d{24})")) -> dict:

The error points me to the pydantic documentation, but I don't understand what's wrong. I believe what they suggest there is exactly what fastapi is supposed to do under the hood.

https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

Upvotes: 1

Views: 4462

Answers (1)

MatsLindh
MatsLindh

Reputation: 52882

Since you're limiting the field to int, you can't apply a regex constraint to the field. Instead define the field as str, and the regex can be applied as you want:

async def get_serial(serial: str = Path(..., regex=r"(?:\d{18}|\d{24})")) -> dict:

This is because the int constraint takes precedence over the regex constraint, and is what the error attempts to convey.

Upvotes: 2

Related Questions