Using Enum in FastAPI with Python – #SurenPyTips

Posted by


Enums are a convenient way to define a set of named constants in Python. FastAPI is a modern web framework for building APIs with Python that supports enums out of the box.

In this tutorial, we will go over how to use enums in FastAPI to define a set of allowed values for a request parameter.

First, let’s create an enum class that represents a set of allowed values. We can do this by using the Enum class from the enum module:

from enum import Enum

class FruitEnum(Enum):
    APPLE = 'apple'
    BANANA = 'banana'
    ORANGE = 'orange'

Next, let’s create a FastAPI application and define a route that accepts a parameter with one of the enum values:

from fastapi import FastAPI
from enum import Enum
from pydantic import BaseModel

app = FastAPI()

class FruitEnum(str, Enum):
    APPLE = 'apple'
    BANANA = 'banana'
    ORANGE = 'orange'

class FruitRequest(BaseModel):
    fruit: FruitEnum

@app.get("/fruit-choice/")
async def choose_fruit(choice: FruitEnum):
    return {"chosen_fruit": choice}

In this example, we’ve created a route /fruit-choice/ that accepts a parameter choice with one of the enum values defined in the FruitEnum class. The route handler will return a JSON response with the chosen fruit.

To test the endpoint, you can use tools like curl or Postman to make a GET request to /fruit-choice/ with a query parameter choice set to one of the enum values:

$ curl http://localhost:8000/fruit-choice/?choice=apple
{"chosen_fruit":"apple"}

FastAPI will automatically validate the incoming request parameter against the enum values defined in the FruitEnum class. If the parameter is not one of the allowed values, FastAPI will return a 422 Unprocessable Entity error.

Enums are a powerful tool for defining a set of allowed values in your API endpoints, and FastAPI makes it easy to work with enums in your web applications. By using enums, you can ensure that your API endpoints accept only valid input values, making your API more robust and less prone to errors.

0 0 votes
Article Rating

Leave a Reply

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@lifestyletv139
14 days ago

Кайф

@ruria_coda
14 days ago

Идеально!

2
0
Would love your thoughts, please comment.x
()
x