Stay Hungry,Stay Foolish!

fastapi-versioning

fastapi-versioning

https://github.com/DeanWay/fastapi-versioning

 

from fastapi import FastAPI
from fastapi_versioning import VersionedFastAPI, version

app = FastAPI(title="My App")


@app.get("/greet")
@version(1, 0)
def greet_with_hello():
    return "Hello"


@app.get("/greet")
@version(1, 1)
def greet_with_hi():
    return "Hi"


app = VersionedFastAPI(app)

 

this will generate two endpoints:

/v1_0/greet
/v1_1/greet
 

as well as:

/docs
/v1_0/docs
/v1_1/docs
/v1_0/openapi.json
/v1_1/openapi.json
 

There's also the possibility of adding a set of additional endpoints that redirect the most recent API version. To do that make the argument enable_latest true:

app = VersionedFastAPI(app, enable_latest=True)
 

this will generate the following additional endpoints:

/latest/greet
/latest/docs
/latest/openapi.json
 

In this example, /latest endpoints will reflect the same data as /v1.1.

Try it out:

pip install pipenv
pipenv install --dev
pipenv run uvicorn example.annotation.app:app
# pipenv run uvicorn example.folder_name.app:app
 

Usage without minor version

from fastapi import FastAPI
from fastapi_versioning import VersionedFastAPI, version

app = FastAPI(title='My App')

@app.get('/greet')
@version(1)
def greet():
  return 'Hello'

@app.get('/greet')
@version(2)
def greet():
  return 'Hi'

app = VersionedFastAPI(app,
    version_format='{major}',
    prefix_format='/v{major}')
 

this will generate two endpoints:

/v1/greet
/v2/greet
 

as well as:

/docs
/v1/docs
/v2/docs
/v1/openapi.json
/v2/openapi.json

 

posted @ 2025-02-21 22:37  lightsong  阅读(13)  评论(0)    收藏  举报
千山鸟飞绝,万径人踪灭