Reputation: 2328
I was trying to find a way to set a default value for Enum
class on Pydantic as well as FastAPI docs but I couldn't find how to do this. Here is my enum class:
class ConnectionStatus(str,Enum):
active:"active"
inactive:"inactive"
deprecated:"deprecated"
And I'd like to make active
as default, for example.
Thanks :)
Upvotes: 2
Views: 6206
Reputation: 88659
First of all, your enum class has some syntax error, it should be =
instead of :
. Thus, your ConnectionStatus
will become,
class ConnectionStatus(str, Enum):
active = 'active'
inactive = 'inactive'
deprecated = 'deprecated'
and to set the default value, use the below snippet
from fastapi import FastAPI
from pydantic import BaseModel
from enum import Enum
app = FastAPI()
class ConnectionStatus(str, Enum):
active = 'active'
inactive = 'inactive'
deprecated = 'deprecated'
class SomeModel(BaseModel):
status: ConnectionStatus = ConnectionStatus.active
@app.post("/")
async def some_route(data: SomeModel):
return data
Reference: Enums and Choices - Pydantic Doc
Upvotes: 3