return pydantic model with field names instead of alias as fastapi response

Viewed 4008

I am trying to return my model with the defined field names instead of its aliases.

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

@app.get("/") -> FooModel:
    return FooModel(**{"bar": "baz"})

The response will be {"bar": "baz"} while I want {"foo": "baz"}. I know it's somewhat possible when using the dict method of the model, but it doesn't feel right and messes up the typing of the request handler.

@app.get("/") -> FooModel:
    return FooModel(**{"bar": "baz"}).dict(by_alias=False)

I feel like it should be possible to set this in the config class, but I can't find the right option.

1 Answers

You can add response_model_by_alias=False to path operation decorator. This key is mentioned here in the documentation.

For example:

@app.get("/model", response_model=Model, response_model_by_alias=False)
def read_model():
    return Model(alias="Foo")
Related