api versioning for fastapi web applications
fromfastapiimportFastAPIfromfastapi_versioningimportVersionedFastAPI, versionapp=FastAPI(title='My App')
@app.get('/greet')@version(1, 0)defgreet():
return'Hello'@app.get('/greet')@version(1, 1)defgreet():
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
Try it out:
pip install pipenv
pipenv install --dev
pipenv run uvicorn example.app:app
fromfastapiimportFastAPIfromfastapi_versioningimportVersionedFastAPI, versionapp=FastAPI(title='My App')
@app.get('/greet')@version(1)defgreet():
return'Hello'@app.get('/greet')@version(2)defgreet():
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
It's important to note that only the title from the original FastAPI will be
provided to the VersionedAPI app. If you have any middleware, event handlers
etc these arguments will also need to be provided to the VersionedAPI function
call, as in the example below
fromfastapiimportFastAPI, Requestfromfastapi_versioningimportVersionedFastAPI, versionfromstarlette.middlewareimportMiddlewarefromstarlette.middleware.sessionsimportSessionMiddlewareapp=FastAPI(
title='My App',
description='Greet uses with a nice message',
middleware=[
Middleware(SessionMiddleware, secret_key='mysecretkey')
]
)
@app.get('/greet')@version(1)defgreet(request: Request):
request.session['last_version_used'] =1return'Hello'@app.get('/greet')@version(2)defgreet(request: Request):
request.session['last_version_used'] =2return'Hi'@app.get('/version')deflast_version(request: Request):
returnf'Your last greeting was sent from version {request.session["last_version_used"]}'app=VersionedFastAPI(app,
version_format='{major}',
prefix_format='/v{major}',
description='Greet uses with a nice message',
middleware=[
Middleware(SessionMiddleware, secret_key='mysecretkey')
]
)