How to accept an optional datetime query parameter which is explicitly provided as null? #11497
-
First Check
Commit to Help
Example Codefrom typing import Annotated
import uvicorn
from fastapi import FastAPI, Query
from datetime import datetime
app = FastAPI()
@app.get("/")
def root(dt: Annotated[datetime | None, Query(description="I want to be able to provide `null` for this.")] = None):
return dt
if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", reload=True) Description
Operating SystemLinux Operating System DetailsNo response FastAPI Version0.110.2 Pydantic Version2.7.1 Python VersionPython 3.11.6 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
What about using an Enum? from typing import Annotated
from enum import Enum
import uvicorn
from fastapi import FastAPI, Query
from datetime import datetime
app = FastAPI()
class DtEnum(str, Enum):
null = "null"
@app.get("/")
def root(dt: Annotated[datetime | DtEnum | None, Query(description="...")] = None):
if not dt or dt == DtEnum.null:
return None
return dt Test:
|
Beta Was this translation helpful? Give feedback.
-
You can also exlude this
And by including Final annotation that works as you expected (as I understand what you want), but without all these "null" and "" in json schema:
I don't know whether there is a nicer way to do that.. |
Beta Was this translation helpful? Give feedback.
-
Thank you both for your answers, I also agree that it's a little bit strange to do it at all. I was just wondering as this exactly what is for example produced by |
Beta Was this translation helpful? Give feedback.
null
in thehttp://127.0.0.1:8000/?dt=null
reuest is not an empty value, but a string "null". So, if you want to let clients send this type of requests, you should include it in type annotation.I think you can either use the approach with enum that is shown above, or you can use
Literal['null']
:You can also exlude this
null
from schema by usingSkipJsonSchema
:And by including
Literal['']
you can also su…