0
0
FastapiHow-ToBeginner · 3 min read

How to Use Enum in Path Parameter in FastAPI

In FastAPI, you can use a Python Enum as a path parameter type to restrict the allowed values. Define an Enum class and use it as the type annotation in your path operation function parameter to automatically validate and document the allowed values.
📐

Syntax

To use an Enum in a FastAPI path parameter, first define a Python Enum class with the allowed values. Then, use this Enum as the type for the path parameter in your route function. FastAPI will validate the input and convert it to the Enum member.

  • Enum class: Defines allowed string or integer values.
  • Path parameter: Annotated with the Enum type.
  • Validation: FastAPI checks if the input matches any Enum member.
python
from enum import Enum
from fastapi import FastAPI

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

app = FastAPI()

@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    return {"model_name": model_name}
💻

Example

This example shows a FastAPI app with a path parameter model_name restricted to three model names using an Enum. When you visit /models/alexnet, it returns {"model_name": "alexnet"}. If you try a value not in the enum, FastAPI returns a 422 error.

python
from enum import Enum
from fastapi import FastAPI

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

app = FastAPI()

@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    return {"model_name": model_name}

# Run with: uvicorn filename:app --reload
Output
GET /models/alexnet Response: {"model_name": "alexnet"} GET /models/unknown Response: 422 Unprocessable Entity (validation error)
⚠️

Common Pitfalls

Common mistakes when using Enum in FastAPI path parameters include:

  • Not inheriting from str and Enum together, which can cause issues with JSON serialization.
  • Using values in the path that are not defined in the Enum, leading to validation errors.
  • Forgetting to import Enum from the enum module.

Always inherit your enum from str and Enum for string values to ensure compatibility with FastAPI and OpenAPI docs.

python
from enum import Enum
from fastapi import FastAPI

# Wrong: Enum without str inheritance
class ModelName(Enum):
    alexnet = "alexnet"
    resnet = "resnet"

app = FastAPI()

@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
    return {"model_name": model_name}

# This may cause issues with JSON serialization and docs.

# Correct way:
from enum import Enum

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
📊

Quick Reference

ConceptDescriptionExample
Enum classDefines allowed values for path parameterclass ModelName(str, Enum): alexnet = "alexnet"
Path parameter typeUse Enum as type annotationasync def get_model(model_name: ModelName):
ValidationFastAPI auto-validates input against EnumReturns 422 if invalid
InheritanceInherit from str and Enum for string enumsclass ModelName(str, Enum): ...

Key Takeaways

Use Python Enum classes as path parameter types to restrict allowed values in FastAPI routes.
Always inherit your Enum from str and Enum for proper JSON serialization and OpenAPI docs.
FastAPI automatically validates path parameters against Enum members and returns errors for invalid values.
Define clear Enum members to improve API clarity and reduce errors from invalid inputs.