I am using a Header
named Accept-Version
to handle API versioning in my FastAPI project at the function level. Following fastapi documentation, a sub-class that inherits from str
and from Enum
is used to predefine the version that the header can accept.
As the project goes on, I want to mark the old versions as deprecated without removing it. The code is as follows.
from enum import Enum
from typing import Union
from fastapi import FastAPI, Header
from pydantic import BaseModel
app = FastAPI()
class VersionNumber(str, Enum):
_1_1 = "1.1 (deprecated)"
_1_2 = "1.2"
_1_3 = "1.3"
class Item(BaseModel):
name: str
price: float
@app.post("/items")
async def update_item(item: Union[Item, None], accept_version: VersionNumber=Header(VersionNumber._1_2)):
accept_version = accept_version.replace('(deprecated)', '')
accept_version = float(accept_version)
if accept_version == 1.1:
return item
elif accept_version >= 1.2 and accept_version < 1.3:
return item.dict()["name"], item.dict()["price"]
else:
return item.dict()["name"]
Based on the code above, the Swagger UI is able to show version 1.1
as deprecated, which looks like this.
However, when sending the request, it is accepting 1.1 (deprecated)
instead of 1.1
as a value for Accept-Version
header, which is not desirable. Is there a way to elegantly mark version 1.1
as deprecated and keep the header as 1.1
?