I'm trying to create a fastapi API endpoint that relies on HTTP GET parameters, has them documented and uses fastapi's validation capabilities. Consider the following minimal example:
import fastapi
app = fastapi.FastAPI(
)
@app.get("/endpoint")
def example_endpoint(
par1: int = fastapi.Query(
None,
description="example documentation1",
),
par2: int = fastapi.Query(
None,
description="example documentation2",
),
):
return {"test": par1 + par2}
This has the documentation support and works over HTTP GET parameters, but doesn't validate them - http://localhost:8000/endpoint?par1=2&par2=3 works fine, but http://localhost:8000/endpoint crashes with an internal server error, instead of notifying the user that a parameter was expected. Is there a way to make par1 and par2 required and keep the documentation feature?
Yes, mandatory parameters can be used in query parameters.
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
You can use Ellipsis, If you hadn't seen that ...
before: it is a special single value that makes query required
from fastapi import Query
Query(...,description="example documentation1")
So in your case answer below can do the job
@app.get("/endpoint")
def example_endpoint(
par1: int = fastapi.Query(..., description="example documentation1",),
par2: int = fastapi.Query(..., description="example documentation2",),
):
if par1 and par2:
return {"test": par1 + par2}
raise ValueError("Missing query parameters")
Also you can use example=1
Query(..., description="example documentation2", example=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With