Skip to content

Enhancement: Use Pydantic model_config for determining alias usage in OpenAPI schema #4342

@sobolevn

Description

@sobolevn

Description

Let's say I have this app:

from litestar import Litestar, post
from litestar.openapi import OpenAPIConfig
from litestar.openapi.plugins import SwaggerRenderPlugin
from pydantic import BaseModel, Field

class Item(BaseModel):
    field_name: str = Field(alias="fieldName")


@post("/")
async def handler(data: Item) -> Item:
    return data

app = Litestar(
    route_handlers=[handler],
    openapi_config=OpenAPIConfig(
        title="Test",
        version="1.0.0",
        render_plugins=[SwaggerRenderPlugin()],
    ),
)

It shows me this API docs:

Image

Everything works as expected.
We get Item as an input schema, then return it.

Now, when I change data: Item to be something else, like data: str, my schema changes in an incompatible way :)

@post("/")
async def handler(data: str) -> Item:
    return Item(fieldName=data)

Now it is:

Image

Notice: camelCase -> snake_case. Which will break existing code for existing users of my API.

Which is kinda expected, because .model_dump() by default produces:

>>> Item(fieldName='abc').model_dump()
{'field_name': 'abc'}

But, setting serialize_by_alias also does not change the produced schema:

In [1]: from pydantic import BaseModel, Field, ConfigDict
   ...: 
   ...: class Item(BaseModel):
   ...:     field_name: str = Field(alias="fieldName")
   ...:     model_config = ConfigDict(serialize_by_alias=True)
   ...: 

In [2]: Item(fieldName='abc').model_dump()
Out[2]: {'fieldName': 'abc'}

So, this looks like a bug to me :)

URL to code causing the issue

No response

MCVE

Steps to reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Screenshots

No response

Logs


Litestar Version

2.17.0

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementThis is a new feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions