Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 384
The Fool Avatar asked Dec 28 '25 16:12

The Fool


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")
like image 199
alex_noname Avatar answered Dec 30 '25 06:12

alex_noname



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!