1

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?

wavingtide
  • 1,032
  • 4
  • 19
  • As far as I know, you could add a `middleware`, match for the string in the `header` of the `request` and delete it. Could that be an option? https://fastapi.tiangolo.com/tutorial/middleware – lsabi Dec 15 '22 at 20:23
  • @Isabi Thanks for the suggestion. I believe `middleware` won't help as I am still accepting `1.1 (deprecated)` instead of `1.1` in the `Accept-Version` header? – wavingtide Dec 16 '22 at 01:42
  • Nope, you change the header in the `middleware` and then go on with the normal flow. See https://stackoverflow.com/questions/69934160/python-how-to-manipulate-fastapi-request-headers-to-be-mutable – lsabi Dec 16 '22 at 20:59

0 Answers0