Full answer
Free-text strings let clients send anything. When only a few values make sense (exam terms, sort orders, report formats), declare them as types.
Enum:
python
class Term(str, Enum):
mid = "mid"
final = "final"
supplementary = "supplementary"
@app.get("/results/{term}")
def results(term: Term): ...- Subclassing
str(or usingStrEnumfrom Python 3.11+) makes values JSON-friendly and comparable to strings. - Inside the function,
termis aTermmember: compare withterm is Term.finalor readterm.value. - OpenAPI shows the allowed values, and Swagger UI renders a dropdown.
- Wrong value gives 422 with type
enumand a message listing the options.
Literal:
python
def list_students(order: Literal["asc", "desc"] = "asc"): ...- No extra class; good for a parameter used once.
- Inside the function it is a plain string.
Both work for path, query, header and body fields (in Pydantic models too).
Tips:
- Use enums for values shared across several endpoints and models, so a new value is added in one place.
- Keep enum values stable; they are part of the public API contract. Renaming a value is a breaking change.
- For case-insensitive input, normalise with a validator or a custom
_missing_method on the enum, rather than adding duplicate members.
python
from enum import Enum
from typing import Literal
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Term(str, Enum):
mid = "mid"
final = "final"
supplementary = "supplementary"
class ReportRequest(BaseModel):
term: Term
format: Literal["pdf", "csv"] = "pdf"
@app.get("/results/{term}")
def results(term: Term, order: Literal["asc", "desc"] = "asc"):
return {"term": term.value, "is_final": term is Term.final, "order": order}
@app.post("/reports")
def make_report(req: ReportRequest):
return req
c = TestClient(app)
print(c.get("/results/final?order=desc").json())
err = c.get("/results/annual").json()["detail"][0]
print(err["type"], "|", err["msg"])
print(c.post("/reports", json={"term": "mid", "format": "csv"}).json())
print(c.get("/openapi.json").json()["components"]["schemas"]["Term"]["enum"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'term': 'final', 'is_final': True, 'order': 'desc'} enum | Input should be 'mid', 'final' or 'supplementary' {'term': 'mid', 'format': 'csv'} ['mid', 'final', 'supplementary']
Key points
- Enum or Literal restricts values
- Wrong value gives 422 listing allowed options
- Docs show a dropdown
- str-based Enum is reusable and JSON-friendly
- Enum values are part of the API contract
Common mistakes
- Accepting any string and validating with if-statements in the handler
- Using a plain Enum (not str-based) and getting awkward serialisation
- Renaming enum values and breaking existing clients
- Comparing an enum member to a string with 'is'
Follow-ups
- How would you accept case-insensitive enum values?
- When would you choose Literal over Enum?
- How do enum changes affect API versioning?
Tips
- Show both Enum and Literal
- Mention the docs dropdown and 422 message
- Treat enum values as a contract