Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro· GoogleHugging Face LMArena Human Preference 140K

In Python with FastAPI, I want to expose a fixed list of options, that are identifiers…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. 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?

  2. Gemini Assistant

    Of course! This is a core feature of FastAPI and is handled elegantly using Python's standard Enum class 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

    1. Enum from Python's enum module: You define your fixed list of options as a class that inherits from Enum.
    2. Inherit from str: By also inheriting from str, 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.
    3. Type Hinting: In your path operation function (e.g., your endpoint), you type hint the parameter with your Enum class.

    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

    1. Save the code above as main.py.
    2. Make sure you have FastAPI and an ASGI server like Uvicorn installed:
      pip install "fastapi[all]"
      
    3. 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 the model_name parameter is not just a text box, but a dropdown menu with your three options: alexnet, resnet, and lenet. 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 the model_name parameter in the function get_model is type-hinted as ModelName, FastAPI does the following:

    1. Checks if "resnet" is a valid value in the ModelName enum. It is.
    2. Converts the string "resnet" into the enum member ModelName.resnet.
    3. Calls your function get_model with ModelName.resnet as 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 a 422 Unprocessable Entity error 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.

  3. 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?

  4. Gemini 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 Enum member has a name (the Python identifier) and a value (what it's assigned to). FastAPI, thanks to the str inheritance, uses the value for the public-facing API (documentation, validation) and provides your code with the full enum member object, which has both a .name and a .value attribute.

    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_CASE for 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

    1. Run the App: uvicorn main:app --reload

    2. 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_name parameter will correctly show the values: resnet, alexnet, lenet. FastAPI does not expose your internal Python names (DEEP_RESIDUAL_NETWORK).
    3. 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 ModelName enum and finds the member whose value is "resnet". It finds ModelName.DEEP_RESIDUAL_NETWORK.
      • Conversion: It converts the string into the ModelName.DEEP_RESIDUAL_NETWORK enum member object.
      • Function Call: It calls your get_model function, passing ModelName.DEEP_RESIDUAL_NETWORK as the model_name argument.
    4. Inside Your Code:

      • The print statements in the terminal where you're running uvicorn will 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".
    5. 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_name enum member is serialized back into JSON, FastAPI automatically uses its string value ("resnet"), which is exactly what you want for a consistent API.

    Summary

    FeatureHow it's handled
    Expose OptionsFastAPI uses the string values ("resnet", "alexnet") for the OpenAPI spec and interactive docs.
    Receive ChoiceFastAPI validates the incoming string against the enum's values and converts it to the corresponding enum member.
    Internal Python CodeYou get the full enum member (ModelName.DEEP_RESIDUAL_NETWORK) and can use its .name or .value properties.

    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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.