Fastapi: [BUG] OpenAPI does not recognise default values in data models

Created on 5 Mar 2020  路  6Comments  路  Source: tiangolo/fastapi

Describe the bug

When using a data model for a post endpoint the default values are not shown correctly in /docs UI, but are shown correctly in /redoc UI.

To Reproduce

import fastapi
import pydantic

app = fastapi.FastAPI()


class Item(pydantic.BaseModel):
    name: str = pydantic.Field(default='a')
    description: str = '3'


@app.put("/")
def func(item: Item):
    return {}
  • In /docs, the default values displayed incorrectly:
{
  "name": "string",
  "description": "string"
}
  • in /redoc, the default values are displayed correctly:
{
    "name": "a",
    "description": "3"
}

Environment

  • OS: Linux, Ubuntu
  • FastAPI Version 0.52.0

  • Python version 3.6.9

answered question

Most helpful comment

There is a difference between default and example.

class Item(pydantic.BaseModel):
    name: str = pydantic.Field(default='a', example='a')
    description: str = pydantic.Field(default='3', example='3')

will do what you want.

Might be a nice feature to use the default as an example if example isn't specified

All 6 comments

/docs swagger display the default value with schema.

There is a difference between default and example.

class Item(pydantic.BaseModel):
    name: str = pydantic.Field(default='a', example='a')
    description: str = pydantic.Field(default='3', example='3')

will do what you want.

Might be a nice feature to use the default as an example if example isn't specified

Thanks for the help here everyone! :clap: :bow:

If that solves the original problem, then you can close this issue :heavy_check_mark:

You might also want to check the docs on extra examples: https://fastapi.tiangolo.com/tutorial/schema-extra-example/

Thanks for looking into it, both the explanation (on the difference between example and default) and the suggestion to take it up with OAS / pydantic is helpful for someone who will find this issue after encountering this problem.

However, it won't:

  • Prevent future confusion for users who will intuitively expect pythonic behaviour by specifying one value (the one specified in the typing annotation), instead of using the Field class and specifying both verbosly and repetitively for every field.
  • It doesn't solve the semantic inconsistency between /docs and /redoc UIs demonstrated in the OP.

Yeah, that would actually be a feature request for Swagger UI, not FastAPI.

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings