Hi, is there a recommended way to have a literal null be used as the default value for a property in the generated OpenAPI schema?
In the following example, I'd like the title property to have a default value of null in the generated OpenAPI schema.
from litestar import Litestar, post
from msgspec import Struct
class TodoItem(Struct):
title: str | None = None
@post("/")
async def foo(data: TodoItem) -> None:
pass
app = Litestar(route_handlers=[foo])
Looking at the generated openapi.json, the TodoItem schema does not have a default value for the title property:
"TodoItem": {
"properties": {
"title": {
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
},
"type": "object",
"required": [],
"title": "TodoItem"
}
My current workaround is to create a class and encoder so that it will be serialized the same as None, and then set the property to an instance of the class through app.openapi_schema:
from litestar import Litestar, post
from msgspec import Struct
class TodoItem(Struct):
title: str | None = None
@post("/")
async def foo(data: TodoItem) -> None:
pass
class JSONNull():
pass
def jsonnull_enc_hook(obj):
if isinstance(obj, JSONNull):
return None
raise TypeError(f"Cannot encode objects of type {type(obj)}")
app = Litestar(route_handlers=[foo], type_encoders={JSONNull: jsonnull_enc_hook})
app.openapi_schema.components.schemas["TodoItem"].properties["title"].default = JSONNull()
With the workaround, the JSON looks like
"TodoItem": {
"properties": {
"title": {
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null
}
},
"type": "object",
"required": [],
"title": "TodoItem"
}