API versionizer for FastAPI web applications
Project description
FastAPI Versionizer
Credit
This was inspired by fastapi_versioning.
This project addresses issues with fastapi_versioning
and adds some additional features.
Installation
pip install fastapi-versionizer
Examples
You can find examples in the examples directory.
Summary
FastAPI Versionizer makes API versioning easy.
Here is a simple (and rather contrived) example:
from typing import List
from fastapi import FastAPI, APIRouter
from pydantic import BaseModel
from fastapi_versionizer.versionizer import Versionizer, api_version
class User(BaseModel):
id: int
name: str
class UserV2(BaseModel):
id: int
name: str
age: int
db = {
'users': {}
}
app = FastAPI(
title='test',
redoc_url=None
)
users_router = APIRouter(
prefix='/users',
tags=['Users']
)
@app.get('/status', tags=['Status'])
def get_status() -> str:
return 'Ok'
@api_version(1)
@users_router.get('', deprecated=True)
def get_users() -> List[User]:
return list(user for user in db['users'].values() if isinstance(user, User))
@api_version(1)
@users_router.post('', deprecated=True)
def create_user(user: User) -> User:
db['users'][user.id] = user
return user
@api_version(2)
@users_router.get('')
def get_users_v2() -> List[UserV2]:
return list(user for user in db['users'].values() if isinstance(user, UserV2))
@api_version(2)
@users_router.post('')
def create_user_v2(user: UserV2) -> UserV2:
db['users'][user.id] = user
return user
app.include_router(users_router)
versions = Versionizer(
app=app,
prefix_format='/v{major}',
semantic_version_format='{major}',
latest_prefix='/latest',
sort_routes=True
).versionize()
This will generate the following endpoints:
- GET /openapi.json
- OpenAPI schema with endpoints from all versions
- GET /docs
- Swagger page with endpoints from all versions
- GET /v1/openapi.json
- OpenAPI schema for v1 endpoints
- GET /v1/docs
- Swagger page for v1 endpoints
- GET /v1/status
- GET /v1/users
- POST /v1/users
- GET /v2/openapi.json
- OpenAPI schema for v2 endpoints
- GET /v2/docs
- Swagger page for v2 endpoints
- GET /v2/status
- This gets carried on from v1, where it was introduced, but has the same implementation
- GET /v2/users
- POST /v2/users
- GET /latest/openapi.json
- OpenAPI schema for latest (i.e. v2) endpoints
- GET /latest/docs
- Swagger page for latest (i.e. v2) endpoints
- GET /latest/status
- GET /latest/users
- POST /latest/users
Details
FastAPI Versionizer works by modifying a FastAPI app in place, adding versioned routes and proper docs pages.
Routes are annotated with version information, using the @api_version
decorator.
Using this decorator, you can specify the version (major and/or minor) that the route was introduced.
You can also specify the first version when the route should be considered deprecated or even removed.
Each new version will include all routes from previous versions that have not been overridden or marked for removal.
An APIRouter will be created for each version, with the URL prefix defined by the prefix_format
parameter described below,
Versionizer Parameters
- app
- The FastAPI you want to version
- prefix_format
- Used to build the version path prefix for routes.
- It should contain either "{major}" or "{minor}" or both.
- Examples: "/v{major}", "/v{major}_{minor}"
- semantic_version_format
- Used to build the semantic version, which is shown in docs.
- Examples: "{major}", "{major}.{minor}"
- default_version
- Default version used if a route is not annotated with @api_version.
- latest_prefix
- If this is given, the routes in your latest version will be a given a separate prefix alias.
- For example, if latest_prefix='latest', latest version is 1, and you have routes: "GET /v1/a" and "POST /v1/b", then "GET /latest/a" and "POST /latest/b" will also be added.
- include_main_docs
- If True, docs page(s) will be created at the root, with all versioned routes included
- include_main_openapi_route
- If True, an OpenAPI route will be created at the root, with all versioned routes included
- include_version_docs
- If True, docs page(s) will be created for each version
- include_version_openapi_route
- If True, an OpenAPI route will be created for each version
- include_versions_route
- If True, a "GET /versions" route will be added, which includes information about all API versions
- sort_routes
- If True, all routes will be naturally sorted by path within each version.
- If you have included the main docs page, the routes are sorted within each version, and versions are sorted from earliest to latest. If you have added a "latest" alias, its routes will be listed last.
- callback
- A function that is called each time a version router is created and all its routes have been added.
- It is called before the router has been added to the root FastAPI app.
- This function should not return anything and has the following parameters:
- Version router
- Version (in tuple form)
- Version path prefix
Docs Customization
- There are various parameters mentioned above for controlling which docs page are generated.
- The swagger and redoc URL paths can be controlled by setting your FastAPI app's
docs_url
andredoc_url
.- If these are set to None, docs pages will not be generated.
- Swagger UI parameters can be controlled by setting your FastAPI app's
swagger_ui_parameters
- If you want to customize your docs beyond what FastAPI Versionizer can handle, you can do the following:
- Set
include_main_docs
andinclude_version_docs
to False - Set
include_main_openapi_route
andinclude_version_openapi_route
to False if you need to customize the OpenAPI schema. - Pass a
callback
param toVersionizer
and add your own docs/OpenAPI routes manually for each version - If you want a "main" docs page, with all versioned routes included, you can manually add a docs/OpenAPI route to the versioned FastAPI app returned by
Versionizer.versionize()
.
- Set
- See the Docs Customization example for more details
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file fastapi_versionizer-4.0.1.tar.gz
.
File metadata
- Download URL: fastapi_versionizer-4.0.1.tar.gz
- Upload date:
- Size: 9.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.10.0 readme-renderer/43.0 requests/2.31.0 requests-toolbelt/1.0.0 urllib3/2.2.1 tqdm/4.66.2 importlib-metadata/7.0.1 keyring/24.3.1 rfc3986/1.5.0 colorama/0.4.6 CPython/3.8.18
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ced631ebefa4aa9774da3d1b77731ea6d3e622fd0d6a6544aac5928d3f1440f4 |
|
MD5 | dea660417413dc1183b83b1be2c9bbc3 |
|
BLAKE2b-256 | d070b7dcc2398bdf3b5fdabbab9ff3a1e98336adeb640195676cf81865f0159b |