Search code examples
pythonjsonjson-deserializationfastapipydantic

Is it possible to change the output alias in pydantic?


Setup:

# Pydantic Models

class TMDB_Category(BaseModel):
    name: str = Field(alias="strCategory")
    description: str = Field(alias="strCategoryDescription")


class TMDB_GetCategoriesResponse(BaseModel):
    categories: list[TMDB_Category]


@router.get(path="category", response_model=TMDB_GetCategoriesResponse)
async def get_all_categories():
    async with httpx.AsyncClient() as client:
        response = await client.get(Endpoint.GET_CATEGORIES)
        return TMDB_GetCategoriesResponse.parse_obj(response.json())

Problem:
Alias is being used when creating a response, and I want to avoid it. I only need this alias to correctly map the incoming data but when returning a response, I want to use actual field names.

Actual response:

{
  "categories": [
    {
      "strCategory": "Beef",
      "strCategoryDescription": "Beef is ..."
    },
    {
      "strCategory": "Chicken",
      "strCategoryDescription": "Chicken is ..."
    }
}

Expected response:

{
  "categories": [
    {
      "name": "Beef",
      "description": "Beef is ..."
    },
    {
      "name": "Chicken",
      "description": "Chicken is ..."
    }
}

Solution

  • Use the Config option by_alias.

    
    from fastapi import FastAPI, Path, Query
    from pydantic import BaseModel, Field
    
    app = FastAPI()
    
    class Item(BaseModel):
        name: str = Field(..., alias="keck")
    
    @app.post("/item")
    async def read_items(
        item: Item,
    ):
        return item.dict(by_alias=False)
    

    Given the request:

    {
      "keck": "string"
    }
    

    this will return

    {
      "name": "string"
    }