mike-oakley / openapi-pydantic

Pydantic OpenAPI schema implementation
Other
66 stars 10 forks source link

Bug: invalid OpenAPI 3.0.x spec for Pydantic fields with examples #51

Open kolditz-senec opened 1 week ago

kolditz-senec commented 1 week ago

When using a Pydantic Field with examples in a request or response model, the generated OpenAPI 3.0.x spec is invalid. See #45 for details.

Here is a test case that can be added to https://github.com/mike-oakley/openapi-pydantic/blob/main/tests/v3_0/test_validated_schema.py:

def test_field_with_examples() -> None:
    class SampleModel(BaseModel):
        field: str = Field(default="default", examples=["example1", "example2"])

    part_api = construct_sample_api(SampleModel)

    api = construct_open_api_with_schema_class(part_api)
    assert api.components is not None
    assert api.components.schemas is not None

    if PYDANTIC_V2:
        json_api: Any = api.model_dump(mode="json", by_alias=True, exclude_none=True)
    else:
        json_api: Any = api.dict(by_alias=True, exclude_none=True)

    validate(json_api)

As a simple fix, we currently replace this line in our fork:

-    example: Optional[Any] = None
+    examples: Optional[Any] = Field(default=None, alias="example")