You can also declare bool types, and they will be converted:
fromfastapiimportFastAPIapp=FastAPI()@app.get("/items/{item_id}")asyncdefread_item(item_id:str,q:str|None=None,short:bool=False):item={"item_id":item_id}ifq:item.update({"q":q})ifnotshort:item.update({"description":"This is an amazing item that has a long description"})returnitem
fromtypingimportUnionfromfastapiimportFastAPIapp=FastAPI()@app.get("/items/{item_id}")asyncdefread_item(item_id:str,q:Union[str,None]=None,short:bool=False):item={"item_id":item_id}ifq:item.update({"q":q})ifnotshort:item.update({"description":"This is an amazing item that has a long description"})returnitem
In this case, if you go to:
http://127.0.0.1:8000/items/foo?short=1
or
http://127.0.0.1:8000/items/foo?short=True
or
http://127.0.0.1:8000/items/foo?short=true
or
http://127.0.0.1:8000/items/foo?short=on
or
http://127.0.0.1:8000/items/foo?short=yes
or any other case variation (uppercase, first letter in uppercase, etc), your function will see the parameter short with a bool value of True. Otherwise as False.
You can declare multiple path parameters and query parameters at the same time, FastAPI knows which is which.
And you don't have to declare them in any specific order.
They will be detected by name:
fromfastapiimportFastAPIapp=FastAPI()@app.get("/users/{user_id}/items/{item_id}")asyncdefread_user_item(user_id:int,item_id:str,q:str|None=None,short:bool=False):item={"item_id":item_id,"owner_id":user_id}ifq:item.update({"q":q})ifnotshort:item.update({"description":"This is an amazing item that has a long description"})returnitem
fromtypingimportUnionfromfastapiimportFastAPIapp=FastAPI()@app.get("/users/{user_id}/items/{item_id}")asyncdefread_user_item(user_id:int,item_id:str,q:Union[str,None]=None,short:bool=False):item={"item_id":item_id,"owner_id":user_id}ifq:item.update({"q":q})ifnotshort:item.update({"description":"This is an amazing item that has a long description"})returnitem