[Python] FastAPI Swagger UI shows alias instead of original field name in response schema

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following FastAPI code using Pydantic:

    from fastapi import FastAPI
    from fastapi.routing import APIRouter
    from pydantic import BaseModel, Field
    from typing import Optional

    app = FastAPI()
    router = APIRouter()

    class UserSchema(BaseModel):
    user_name: Optional[str] = Field(None, alias="name")

    class Config:
    populate_by_name = True

    @router.get(
    "/user",
    tags=["user"],
    summary="Get user",
    response_model=UserSchema,
    response_model_by_alias = False
    )
    async def get_user():
    user_data = {"name": "John Doe"}
    return UserSchema(**user_data).model_dump()

    Current Behavior


    API Response: (Correct)

    {
    "user_name": "John Doe"
    }


    Swagger UI Response Schema: (Incorrect — it shows the alias instead of the original field name) Image

    {
    "name": "string"
    }

    Expected Behavior


    I want the Swagger UI (OpenAPI) response schema to show the field name user_name instead of the alias name.

    What I've Tried

    1. Using by_alias=False when serializing the response.

    async def get_user():
    user_data = {"name": "John Doe"}
    return UserSchema(**user_data).model_dump(by_alias=False)

    1. Adding populate_by_name = True in the Pydantic model's Config.

    class UserSchema(BaseModel):
    user_name: Optional[str] = Field(None, alias="name")

    class Config:
    populate_by_name = True

    1. Setting response_model_by_alias = False in the route

    @router.get(
    "/user",
    tags=["user"],
    summary="Get user",
    response_model=UserSchema,
    response_model_by_alias = False
    )


    How can I configure FastAPI to make the Swagger UI display the field name (user_name) instead of the alias (name)?

    Continue reading...

Compartilhe esta Página