1

Is it possible to add multiple select for a dropdown in fastapi openapi? I only manage to select one.

  • if I set Optional[List] it wont run, the enum?).
  • if I set {[ids]}in the routes openapi says it is a array and no dropdown.
@app.get("/schedules")
@app.get("/schedules/{ids}", include_in_schema=False)
@app.get("/schedules/{ids}/{active}")
async def GetScedules(
  ids:Optional[str]=Query(None, enum=[str(id) for id in appconfig['projectids']]),
  active:Optional[str]=Query(None, enum=["active", "notactive"])):
  """ list gitlab schedules sorted on projectids """
  if isinstance(ids, str): # convert str to list
    if ',' in ids:
      ids = ids.split(',')
    else:
      ids = [ids]

I can only choose one, but like to choose multiple

MortenB
  • 2,749
  • 1
  • 31
  • 35
  • 1
    The param needs to be an array of enum, something like `Optional[List[YourEnum]]`. – Helen Dec 09 '22 at 14:08
  • 1
    You might find [this](https://stackoverflow.com/a/74370808/17865804), as well as [this](https://stackoverflow.com/a/73401333/17865804) and [this](https://stackoverflow.com/a/76131490/17865804) helpful – Chris Aug 11 '23 at 05:07

1 Answers1

1

I recommend you to use Pydantic dataclass as shown bellow. You can find more information in this fastapi issue link

from typing import Optional, List
from enum import Enum

from fastapi import FastAPI, Query, Depends
from pydantic.dataclasses import dataclass

app = FastAPI()

appconfig = {"projectsids": ["1", "2", "3"]}
enum = Enum("enum", {str(i):i for i in appconfig['projectsids']})

@dataclass
class ScheduleModel:
    ids_in: Optional[List[enum]] = Query(None)

@app.get("/schedules")
    async def GetSchedules(
    ids: ScheduleModel=Depends(),
    activate: Optional[str]=Query(None, enum=["activate", "notactive"])
):

    if isinstance(ids, ScheduleModel):
        if ids.ids_in and "," in ids.ids_in:
            ids = ids.split(",")
        else:
            ids = [ids]
    
        return {"ids": ids, "active": activate}
Felix D.
  • 133
  • 8