8

I'm trying to allow null in the JSON schema for this object:

from pydantic import BaseModel
from typing import Optional

class NextSong(BaseModel):
    song_title: Optional[str] = ...

but the schema which results is as follows:

{
    "title": "NextSong",
    "type": "object",
    "properties": {
        "song_title": {
            "title": "Song Title",
            "type": "string"
        }
    },
    "required": ["song_title"]
}

The resulting schema isn't allowing null for the value of song_title, which isn't as intended, but I'm not sure how else to specify that null is allowed, but that the field is still required.

Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
aleph-null
  • 443
  • 4
  • 11

2 Answers2

1

I think you need OpenAPI nullable flag. It should change the schema and set nullable flag, but this field still will be required.

from pydantic import BaseModel, Field
from typing import Optional

class NextSong(BaseModel):
    song_title: Optional[str] = Field(..., nullable=True)

Resulting schema:

{
    "title": "NextSong",
    "type": "object",
    "properties": {
        "song_title": {
            "title": "Song Title",
            "nullable": true,
            "type": "string"
            }
        },
    "required": ["song_title"]
}
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
Vladislav Latish
  • 307
  • 1
  • 10
-1

try using OR symbol

class NextSong(BaseModel):
    song_title: str|None = ...

note: I'm using python 3.10

Althaf
  • 72
  • 5