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