Is there any way to have custom validation logic in a FastAPI query parameter?
example
I have a FastAPI app with a bunch of request handlers taking Path components as query parameters. For example:
def _raise_if_non_relative_path(path: Path):
if path.is_absolute():
raise HTTPException(
status_code=409,
detail=f"Absolute paths are not allowed, {path} is absolute."
)
@app.get("/new",)
def new_file(where: Path):
_raise_if_non_relative_path(where)
# do save a file
return Response(status_code=requests.codes.ok)
@app.get("/new",)
def delete_file(where: Path):
_raise_if_non_relative_path(where)
# do save a file
return Response(status_code=requests.codes.ok)
I was wondering if there is way to ensure that the handler is not even called when the given file path is absolute.
Now I have to repeat myself with _raise_if_non_relative_path everywhere.
what I tried
fastapi.Query:
This only allows very basic validation (string length and regex). I could define a absolute path regex in this example. But a regex solution is really not generic, I want to validate with a custom function.- Subclass
pathlib.Pathwith validation logic in__init__:
This doesn't work, the type given in the type signature is ignored, and the object in my handler is a regularpathlib.PosixPath. - Use
@app.middleware:
this can work but seems overkill since not all my request handlers deal withPathobjects. class RelativePath(pydantic.Basemodel):
I.e. define a class with singlepathfield, which I can validate however I want. Unfortunately, this does not work for query parameters. If I do this, the request handler insists on having a json content body. Or at least that is what the swagger docs say.