Fastapi: Validate List[str] using regex

Created on 22 Feb 2020  路  3Comments  路  Source: tiangolo/fastapi

Hello :)

How do I validate a list of strings that are sent via POST parameters?

I have this example ...

@app.post("/entity/list")
def query_entity_list(entities: List[str] = Query(None, regex="^[a-z]{5}$")):
   return entities

... and the API function is called by ...

curl -X POST "http://localhost/entity/list/?entities=valid&entities=inv4lid

Is it possible to apply the regex on each item in the entities list?
Currently, the string validation does not working for me.

Thanks in advance!

question

Most helpful comment

You would want to have a specific string type with that contraint. Pydantic has a ConstrainedStr/constr type spcifically for that purpose:

from pydantic import constr

EntryCode = constr(regex="^[a-z]{5}$")

@app.post("/entity/list")
def query_entity_list(entities: List[EntryCode] = Query(None)):
   return entities

All 3 comments

You would want to have a specific string type with that contraint. Pydantic has a ConstrainedStr/constr type spcifically for that purpose:

from pydantic import constr

EntryCode = constr(regex="^[a-z]{5}$")

@app.post("/entity/list")
def query_entity_list(entities: List[EntryCode] = Query(None)):
   return entities

Thank you very much @sm-Fifteen! It works now :)

Thanks for the help here @sm-Fifteen ! :cake:

Thanks @marius-benthin for reporting back and closing the issue :+1:

Was this page helpful?
5 / 5 - 1 ratings