Reputation: 512
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 ?
Upvotes: 5
Views: 6601
Reputation: 34103
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
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
Upvotes: 8