Search code examples
pythonswaggerfastapiopenapi

Is it possible to have a required query parameter with a default value on FastAPI?


I am trying to make a query parameter required but give it a default value on FastAPI, but i am not finding anything on their user guide.

On openapi, it would be something like this:

parameters:
      - name: "some_name"
        in: "query"
        description: "a description"
        required: true
        type: "string"
        default: "First"
        enum:
        - "First"
        - "Second"
        - "Third"

as you can see required is assigned to true and i have a default value ("first") With fastapi i have this:

class ModelNames(str, Enum):
  first = "first"
  second = "second"
  third = "third"


@app.post("/path")
async def this_function(
    modelInstance = Query(
      default=Required, # i would like to somehow assign "first" and Required to default 
      description="a description"
    )
  ):
  return None

I've tried directly assigning "first" but it makes it optional.


Solution

  • Required parameter can't get default value by design

    You can't.

    If you want to define a default value for the side effect of a custom example value, use the example parameter instead.

    https://fastapi.tiangolo.com/tutorial/schema-extra-example/#example-and-examples-in-openapi