Skip to content

Conversation

@pressogh
Copy link

Hello!

I've encountered an issue in FastAPI's openapi.json generation for parameter inputs (Query, Header, Cookie). When using alias for field names in Pydantic models, the alias appears correctly in the generated schema. However, when using validation_alias, it is ignored and the original field name is shown instead.

To demonstrate this behavior, I’ve included minimal reproducible examples along with corresponding Swagger UI screenshots.

With alias

from pydantic import BaseModel, Field
from typing import Annotated

from fastapi import FastAPI, Header, Query, Cookie


class DataModel(BaseModel):
    foo: str = Field(..., alias="bar")


app = FastAPI()


@app.get("/test")
def test(
        query: Annotated[DataModel, Query(...)],
        header: Annotated[DataModel, Header(...)],
        cookie: Annotated[DataModel, Cookie(...)]
):
    return "Received: " + str(query) + ", " + str(header) + ", " + str(cookie)
image

With validation_alias

from pydantic import BaseModel, Field
from typing import Annotated

from fastapi import FastAPI, Header, Query, Cookie


class DataModel(BaseModel):
    foo: str = Field(..., validation_alias="bar")


app = FastAPI()


@app.get("/test")
def test(
        query: Annotated[DataModel, Query(...)],
        header: Annotated[DataModel, Header(...)],
        cookie: Annotated[DataModel, Cookie(...)]
):
    return "Received: " + str(query) + ", " + str(header) + ", " + str(cookie)
image

As shown above, even though validation_alias="bar" is set, the OpenAPI schema still uses "foo".

Upon inspecting the parameter generation logic, I found that the name used in the schema is determined via the field alias:

name = param.alias

This uses Pydantic’s ModelField logic, where alias is returned if present; otherwise, the field name is used:

@dataclass
class ModelField:
field_info: FieldInfo
name: str
mode: Literal["validation", "serialization"] = "validation"
@property
def alias(self) -> str:
a = self.field_info.alias
return a if a is not None else self.name

Proposed Change

This PR modifies the alias resolution logic in ModelField to prioritize validation_alias or serialization_alias, depending on mode, instead of defaulting to alias alone.

Thanks for taking the time to review this!

@pressogh pressogh closed this Jun 29, 2025
@pressogh pressogh reopened this Jun 29, 2025
@pressogh pressogh marked this pull request as draft June 29, 2025 13:40
@github-actions github-actions bot added the conflicts Automatically generated when a PR has a merge conflict label Oct 11, 2025
@github-actions
Copy link
Contributor

This pull request has a merge conflict that needs to be resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conflicts Automatically generated when a PR has a merge conflict

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant