How to allow only ISO8601 timestamp in query parameter #9938
-
First Check
Commit to Help
Example Codefrom datetime import datetime
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/test")
def test_route(time_1: datetime = Query()):
print(time_1) # This is always a datetime
return time_1DescriptionCase 1:
Case 2:
This is fine, and expected. But I need to not allow case 2, and throw error if case 1. Meaning if time_1 is not a valid ISOFormat, I want to throw error. These are the solutions I tried. Solution I tried:This validates the query param, but raising ValueError here returns "Internal Server Error". So needed to add an exception handler, and so the updated code: Problem with Solution:
but expected Operating SystemLinux, macOS Operating System DetailsEnviroments:
FastAPI Version0.81.0 Python Version3.9.16 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
What happens if you return a |
Beta Was this translation helpful? Give feedback.
-
|
You can implement this using from datetime import datetime
from typing import Annotated, TypeAlias
from fastapi import FastAPI, Query
from pydantic import PlainValidator
app = FastAPI()
def validate_date_time(value: str):
try:
return datetime.strptime(value, "%Y-%m-%dT%H:%M%z")
except ValueError as error:
raise ValueError("Invalid datetime") from error
MyDateTime: TypeAlias = Annotated[datetime, PlainValidator(validate_date_time)]
@app.get("/test")
def test_route(time_1: Annotated[MyDateTime, Query(description="ISO8601 timestamp")]):
print(time_1) # This is always a datetime
return time_1 |
Beta Was this translation helpful? Give feedback.
You can implement this using
PlainValidator: