Search code examples
pythonswaggerfastapipydanticuvicorn

how to type a variable in FastApi-SwaggerUI with hyphen in its name?


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.


Solution

  • 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.