15

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.

The Fool
  • 16,715
  • 5
  • 52
  • 86

1 Answers1

27

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")
alex_noname
  • 26,459
  • 5
  • 69
  • 86
  • 1
    Ok thanks. Do you know how to make the docs show the the same fields? At the moment they show the alias as response and as schema which isnt great. – The Fool Oct 22 '21 at 16:42
  • 4
    I’m afraid this is impossible. According to [that](https://github.com/tiangolo/fastapi/pull/1642) solution is to create another output model. – alex_noname Oct 22 '21 at 17:16
  • alright. Now thinking about and experimenting with it, Isn't your example flawed in that it will serialize and validate the data twice? Should we not just return a dict from the handler, since fastapi will take the return value and stick it into the provided model class? – The Fool Oct 22 '21 at 18:32
  • fastapi, will check what type is returned. So it wont serialize twice. https://github.com/tiangolo/fastapi/blob/5905c3f740c8590f1a370e36b99b760f1ee7b828/fastapi/routing.py#L71 – The Fool Jan 15 '23 at 22:38