5

If I send a request to this API:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Response(BaseModel):
    var_name: str

@app.put("/", response_model=Response)
def simple_server(a: str):
    response = Response(var_name=a)
    return response

I get a response which this json file {"var_name1": "a"}. In addition, I get a very beautiful Swagger UI that illustrate the fields of response.

My question is, how can I get this json file {"var-name1": "a"} (this is with a hyphen instead of an underscore) with the same nice typing in Swagger docs?

Obviously, I cannot name the var_name attribute var-name in Response dataclass.

MKMS
  • 117
  • 7
  • You can alias field names: https://pydantic-docs.helpmanual.io/usage/model_config/#alias-precedence- so maybe `var_name: str = Field(..., alias='var-name')` does what you need? – MatsLindh Nov 04 '21 at 20:57

1 Answers1

11

Modify your pydantic object slightly:

from pydantic import BaseModel, Field

class Response(BaseModel):
    var_name: str = Field(alias="var-name")

    class Config:
        allow_population_by_field_name = True

The allow_population_by_field_name option is needed to allow creating object with field name, without it you could instantiate it only with alias name.

kosciej16
  • 6,294
  • 1
  • 18
  • 29