In FastAPI, you can use Python's enum.Enum to define a fixed list of options and have FastAPI automatically validate and convert incoming request data into the appropriate enum member.
Here's a step-by-step example showing how to expose an enum as a query parameter or request body, and get the corresponding enum value in your endpoint:
✅ Step 1: Define your Enum
from enum import Enum
class Color(str, Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
Using str as a base class makes the values be treated as strings, which is useful for URL parameters, query params, etc.
✅ Step 2: Use the Enum in a route (Query Parameter Example)
from fastapi import FastAPI
app = FastAPI()
@app.get("/choose-color")
async def choose_color(color: Color):
return {"message": f"You chose color {color.value}"}
When someone calls /choose-color?color=red, FastAPI will:
- Validate that
"red" is one of the allowed values (Color.RED)
- Pass the actual
Color.RED enum object to your function
- You can access
.value to get the string "red"
✅ Step 3: Use the Enum in a Request Body (Pydantic Model)
If you're using a POST request with a JSON body:
from pydantic import BaseModel
from enum import Enum
class Color(str, Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
class ColorRequest(BaseModel):
color: Color
@app.post("/choose-color")
async def choose_color(request: ColorRequest):
return {"message": f"You chose color {request.color.value}"}
Now when the client sends:
{
"color": "green"
}
FastAPI will parse it into the Color.GREEN enum value.
✅ Bonus: List Available Options in Docs
FastAPI's Swagger and ReDoc UIs will automatically show the available enum options in both cases — making it clear what the valid inputs are.
🧪 Example cURL Requests
For query param version:
curl "http://localhost:8000/choose-color?color=green"
For body version:
curl -X POST http://localhost:8000/choose-color \
-H "Content-Type: application/json" \
-d '{"color": "blue"}'
✅ Summary
You can achieve this by:
- Defining a
str-based Enum
- Using it directly in path/query parameters or inside Pydantic models
- Accessing
.value (or other attributes) inside your endpoint logic
Let me know if you want to include descriptions, labels, or custom validation!