How to add drop down menu to Swagger UI autodocs based on BaseModel using FastAPI?

Question:

I have this following class:

class Quiz(BaseModel):
    question: str
    subject: str
    choice: str = Query(choices=('eu', 'us', 'cn', 'ru'))
         

I can render the form bases on this class like this

@api.post("/postdata")
def post_data(form_data: Quiz = Depends()):
    return form_data

How can I display a drop down list for choice field ?

Asked By: aba2s

||

Answers:

Option 1

Use literal values. Literal type is a new feature of the Python standard library as of Python 3.8 (prior to Python 3.8, it requires the typing-extensions package) and is supported by Pydantic. Example:

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from typing import Literal

app = FastAPI()
    
class Quiz(BaseModel):
    question: str
    subject: str
    choice: Literal['eu', 'us', 'cn', 'ru'] = 'us'

@app.post('/submit')
def post_data(data: Quiz = Depends()):
    return data

Option 2

Use Enums (also, see Python’s enum module, as well as FastAPI’s documentation on Predefined values). By having your Enum sub-class inheriting from str, the API docs will be able to know that the values must be of type string and will be able to render correctly. Example:

from fastapi import FastAPI, Depends
from pydantic import BaseModel
from enum import Enum

app = FastAPI()

class Country(str, Enum):
    eu = 'eu'
    us = 'us'
    cn = 'cn'
    ru = 'ru'
    
class Quiz(BaseModel):
    question: str
    subject: str
    choice: Country = Country.us
    
@app.post('/submit')
def post_data(data: Quiz = Depends()):
    return data
Answered By: Chris