I started to learn FastAPI by reading the official documentation. I’m having a bit of difficulty understanding the example which illustrate how to work with Python enumarations. The example in the official documentation is a follows:
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):
if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}
The documentation says that: “The value of the path parameter will be an enumeration member.”
I don’t understand how the path parameter is an enumration member. For me the path parameter will correspond to the enumration value. When I call the endpoint 127.0.0.1:8000/models/alexnet
, the path parameter alexnet
is the value of the Enum member ModelName.alexnet
. I’m not passing the Enumaration object in any way in the request.
So, I’m curious to understand when and how FastAPI makes the “translation” to the enumaration member from the path parameter in the call. Because it seems that the path parameter alexnet
is implicitly translated to ModelName.alexnet
.