In Python with FastAPI, I want to expose a fixed list of options, that are identifiers…
- User
In Python with FastAPI, I want to expose a fixed list of options, that are identifiers for a enum. When receiving the request with the callers choice, I want to get passed the associated enum value. How can I achieve this?
Assistant
Of course! This is a core feature of FastAPI and is handled elegantly using Python's standard
Enumclass and type hints. FastAPI's integration with Pydantic allows it to automatically validate incoming data against the enum and convert it to the corresponding enum member.Here is a complete, step-by-step guide and a runnable example.
The Key Concepts
Enumfrom Python'senummodule: You define your fixed list of options as a class that inherits fromEnum.- Inherit from
str: By also inheriting fromstr, you tell FastAPI/Pydantic that the string value of the enum member (e.g.,"alexnet") is its canonical representation. This is what enables the automatic conversion from the incoming request string. - Type Hinting: In your path operation function (e.g., your endpoint), you type hint the parameter with your
Enumclass.
FastAPI does the rest:
- It automatically validates that the incoming value is one of the valid members of the enum.
- It converts the incoming string into the actual enum member object.
- It generates beautiful OpenAPI (Swagger) documentation with a dropdown menu of the available options.
Complete Code Example
Let's create an API for a machine learning model service, where a user can select a specific model by its name.
# main.py from enum import Enum from fastapi import FastAPI # 1. Define the Enum with string values # Inheriting from `str` is crucial for FastAPI to treat the enum # members as their string values. class ModelName(str, Enum): alexnet = "alexnet" resnet = "resnet" lenet = "lenet" # 2. Create the FastAPI app instance app = FastAPI() # 3. Create the endpoint using the Enum as a type hint # We'll use a path parameter here, but it works the same for query parameters. @app.get("/models/{model_name}") async def get_model(model_name: ModelName): """ Get information about a specific machine learning model. """ # By the time this code runs, `model_name` is already a member of the ModelName enum. # It is NOT a string. FastAPI has handled the validation and conversion. # You can now use standard enum comparisons if model_name is ModelName.resnet: return { "model_name": model_name, "message": "This is a deep residual network!", "details": {"name": model_name.name, "value": model_name.value} } if model_name.value == "lenet": # You can also compare using the .value attribute return { "model_name": model_name, "message": "This is a classic convolutional network!", "details": {"name": model_name.name, "value": model_name.value} } # Handle the remaining case return { "model_name": model_name, "message": "A foundational CNN model.", "details": {"name": model_name.name, "value": model_name.value} } # Example with a query parameter @app.get("/search/") async def search_model(model: ModelName = ModelName.resnet): """ Search using a model name as a query parameter. Defaults to resnet if not provided. """ return { "query_model": model, "message": f"You searched for the model: {model.value}" }How to Run the App
- Save the code above as
main.py. - Make sure you have FastAPI and an ASGI server like Uvicorn installed:
pip install "fastapi[all]" - Run the server from your terminal:
uvicorn main:app --reload
How It Works
1. Interactive Documentation (Exposing the Options)
Navigate to
http://127.0.0.1:8000/docs. You will see the auto-generated Swagger UI.For the
/models/{model_name}endpoint, you'll see that themodel_nameparameter is not just a text box, but a dropdown menu with your three options:alexnet,resnet, andlenet. This is how FastAPI "exposes the fixed list of options" to the caller.2. Successful Request (Receiving the Enum Value)
If a user makes a request to
http://127.0.0.1:8000/models/resnet, FastAPI sees the path parameter"resnet". Because themodel_nameparameter in the functionget_modelis type-hinted asModelName, FastAPI does the following:- Checks if
"resnet"is a valid value in theModelNameenum. It is. - Converts the string
"resnet"into the enum memberModelName.resnet. - Calls your function
get_modelwithModelName.resnetas the argument.
The response will be:
{ "model_name": "resnet", "message": "This is a deep residual network!", "details": { "name": "resnet", "value": "resnet" } }3. Validation Error
If a user tries to use an invalid identifier, like
http://127.0.0.1:8000/models/vgg, FastAPI's validation layer kicks in automatically. It will return a422 Unprocessable Entityerror with a helpful JSON body explaining what went wrong.{ "detail": [ { "loc": [ "path", "model_name" ], "msg": "value is not a valid enumeration member; permitted: 'alexnet', 'resnet', 'lenet'", "type": "type_error.enum", "ctx": { "enum_values": [ "alexnet", "resnet", "lenet" ] } } ] }You get all this rich, automatic behavior just by using standard Python features.
- User
This only works if the value is same as the enum field name. How can I expose a value different from it's name?
Assistant
Excellent question! You've hit on a very common and practical requirement. The previous example was a simplified case. The good news is that FastAPI and Pydantic handle this scenario just as elegantly.
The key is to understand that a Python
Enummember has a name (the Python identifier) and a value (what it's assigned to). FastAPI, thanks to thestrinheritance, uses the value for the public-facing API (documentation, validation) and provides your code with the full enum member object, which has both a.nameand a.valueattribute.You don't need to change anything about how you use it in FastAPI, only how you define the enum.
The Solution: Assign Different Values
Simply assign the string value you want to expose in the API to the enum member name you want to use in your Python code.
Let's adapt the previous example. We'll use more descriptive, "Pythonic" names (like
UPPER_SNAKE_CASEfor constants) for our internal code, but expose simple, lowercase strings in the API.
Updated Code Example
# main.py from enum import Enum from fastapi import FastAPI # 1. Define the Enum # The MEMBER_NAME is for your Python code. # The "value" is what's used in the API. class ModelName(str, Enum): DEEP_RESIDUAL_NETWORK = "resnet" ALEXS_CNN = "alexnet" YANN_LECUNS_NET = "lenet" app = FastAPI() @app.get("/models/{model_name}") async def get_model(model_name: ModelName): """ Get information about a specific machine learning model. The dropdown in the docs will show 'resnet', 'alexnet', 'lenet'. """ # Inside this function, `model_name` is an enum member. # You can compare it directly with the Python member name. # Let's see what we received: print(f"Received enum member: {repr(model_name)}") print(f"Member name (identifier): {model_name.name}") print(f"Member value (API string): {model_name.value}") # You work with the Python identifier in your code logic if model_name is ModelName.DEEP_RESIDUAL_NETWORK: return { "message": "This is a deep residual network!", # The JSON response will automatically use the value "resnet" "model_info": { "selected_model": model_name, "python_identifier": model_name.name, "api_value": model_name.value } } if model_name is ModelName.ALEXS_CNN: return { "message": "A foundational CNN model.", "model_info": { "selected_model": model_name, "python_identifier": model_name.name, "api_value": model_name.value } } return { "message": "This is a classic convolutional network!", "model_info": { "selected_model": model_name, "python_identifier": model_name.name, "api_value": model_name.value } }How It Works: The Breakdown
-
Run the App:
uvicorn main:app --reload -
Exposing the Options (API Docs):
- Navigate to
http://127.0.0.1:8000/docs. - Look at the
/models/{model_name}endpoint. - The dropdown for the
model_nameparameter will correctly show the values:resnet,alexnet,lenet. FastAPI does not expose your internal Python names (DEEP_RESIDUAL_NETWORK).
- Navigate to
-
Receiving the Enum Value (Request Handling):
- Use the "Try it out" button in the docs and select
resnet. Or, make a request directly:curl http://127.0.0.1:8000/models/resnet. - Validation: FastAPI receives the incoming string
"resnet". - Matching: It checks the
ModelNameenum and finds the member whose value is"resnet". It findsModelName.DEEP_RESIDUAL_NETWORK. - Conversion: It converts the string into the
ModelName.DEEP_RESIDUAL_NETWORKenum member object. - Function Call: It calls your
get_modelfunction, passingModelName.DEEP_RESIDUAL_NETWORKas themodel_nameargument.
- Use the "Try it out" button in the docs and select
-
Inside Your Code:
- The
printstatements in the terminal where you're runninguvicornwill show:Received enum member: <ModelName.DEEP_RESIDUAL_NETWORK: 'resnet'> Member name (identifier): DEEP_RESIDUAL_NETWORK Member value (API string): resnet - Your
if model_name is ModelName.DEEP_RESIDUAL_NETWORK:comparison works perfectly. This makes your code more readable and robust, as you're not relying on "magic strings" like"resnet".
- The
-
Response:
- The JSON response sent back to the client will be:
{ "message": "This is a deep residual network!", "model_info": { "selected_model": "resnet", "python_identifier": "DEEP_RESIDUAL_NETWORK", "api_value": "resnet" } } - Notice that when the
model_nameenum member is serialized back into JSON, FastAPI automatically uses its string value ("resnet"), which is exactly what you want for a consistent API.
- The JSON response sent back to the client will be:
Summary
Feature How it's handled Expose Options FastAPI uses the string values ( "resnet","alexnet") for the OpenAPI spec and interactive docs.Receive Choice FastAPI validates the incoming string against the enum's values and converts it to the corresponding enum member. Internal Python Code You get the full enum member ( ModelName.DEEP_RESIDUAL_NETWORK) and can use its.nameor.valueproperties.This powerful separation of concerns allows you to maintain clean, readable, and type-safe Python code internally while exposing a simple, user-friendly string-based API externally.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.