-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
Closed
Labels
Description
First Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn't find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google "How to X in FastAPI" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
def validate_date(date: str):
try:
return datetime.strptime(date, "%Y-%m-%d").date
except ValueError:
raise HTTPException(
status_code=400,
detail="Incorrect date format, should be YYYY-MM-DD",
)
@app.get("/endpoint")
async def handler(
required_date: str = Depends(validate_date),
optional_date: str | None = None
):
return "hello"Description
I wanted to add a validator for the parameters "required_date" and "optional_date" but I must create two functions to handle that because one of them is optional.
Wanted Solution
I would like to see an option in Depends() that let me pass parameters to that callable dependency.
Wanted Code
def validate_date(date: str, is_required: bool = True):
if date is None:
if is_required:
raise HTTPException(400, f"{date=} is required.")
return None
try:
return datetime.strptime(date, "%Y-%m-%d").date
except ValueError:
raise HTTPException(
status_code=400,
detail="Incorrect date format, should be YYYY-MM-DD",
)
@app.get("/endpoint")
async def handler(
required_date: str = Depends(validate_date),
optional_date: str | None = Depends(validate_date, parameters={"is_required": False})
):
return "hello"Alternatives
Handle input validators in some other cooler way.
Operating System
Windows
Operating System Details
No response
FastAPI Version
0.85.2
Python Version
Python 3.11.0
Additional Context
Another suggestion.
Add "validator" parameter to Query() where it takes a callable to validate that value with the previous suggestion applied (callable parameters).
Sorry in advance if there is an existing approach to what I am trying to do.
Reactions are currently unavailable