I would like to use this regex for the "asin" query.
What's wrong with what I am doing.
None of the test strings here https://regexr.com/3gk2s, are validate with that regex.
@router.post("/product", tags=["products"])
async def create_product(product: Product, asin: str = Query(None, regex='/(?:[/dp/]|$)([A-Z0-9]{10})/g')):
""" Create a product """
product_dict = product.dict()
if product.asin:
product_dict.update({'is_imported': True})
return product_dict
Thanks
@tiger360 I think you just don't need the starting "/" and ending "/g". Did you test the regex in Python using the builtin re module?
Also, generally you want to put regexes in Python in "raw strings" so you can use regex- specific escapes without Python getting mad. You aren't using any escapes it looks like, but it is best practice. Plus some IDEs will give you extra regexy features!
Just add r to the front of the string like r'(?:[/dp/]|$)([A-Z0-9]{10})'.
yes I tried with python here : https://repl.it/join/xujwnmwd-tiger360
but I still have the error message :
{
"detail": [
{
"loc": [
"query",
"a"
],
"msg": "string does not match regex \"(?:[/dp/]|$)([A-Z0-9]{10})\"",
"type": "value_error.str.regex",
"ctx": {
"pattern": "(?:[/dp/]|$)([A-Z0-9]{10})"
}
}
]
}
with that code with fastapi :
@router.post("/product", tags=["products"])
async def create_product(a: str = Query(None, regex=r'(?:[/dp/]|$)([A-Z0-9]{10})')):
""" Create a product """
return a

I'm pretty sure the regex you provide as a validation needs to match the entire string. Similar to re.fullmatch I believe.
Tweak your regex until it matches the entire URL and you should be all set.
Ok thanks that's what I did
@router.post("/product", tags=["products"])
async def create_product(a: str = Query(None, regex=r'.*/?B[\dA-Z]{9}|\d{9}(X|\d)')):
return a
Thanks for the help here @dbanty ! :clap: :bow:
Thanks for reporting back and closing the issue @tiger360 :+1: