'Python FastAPI ISO 8601 Date format gets http:422 Unprocessable Entity
Python FastAPI cannot process a date with the ISO8601 datetime format. I am calling the server from a Java client and am getting "422 Unprocessable Entity" This is way to strict! I know Node, Java, and Salesforce parse this correctly and truncate the time portion.
Simple Example:
@app.get("/dateParm")
def dateParm( mydate: date = Query("2022-04-06T00:00:00.000Z")) -> bool:
return {"result":True}
Solution 1:[1]
If you want to accept both dates and datetimes, say that you accept either:
@app.get("/")
def dateParm(mydate: date | datetime = Query("2022-04-06T00:00:00.000Z")) -> bool:
return {"result": mydate}
mydate will now either be a date or a datetime, depending on what the user sent you. You can then handle it appropriately as you feel necessary. Also - you need to be careful about the default value. The default value is what is returned if the variable is not present, and will not be converted or parsed further (so in this case - it'll be a string).
However, you can use the dependency system to get what you want and handle both dates and datetime values for a single field - and normalize both to dates. I've also taken the liberty to fix your -> bool return type.
from fastapi import FastAPI, Query, Depends
from typing import Union
from datetime import datetime, date
app = FastAPI()
def either_date_or_datetime(mydate: date | datetime = Query(None)):
if isinstance(mydate, datetime):
mydate = mydate.date()
return mydate
@app.get("/")
def dateParm(mydate: date = Depends(either_date_or_datetime)) -> dict:
return {"result": mydate}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MatsLindh |
