Production-ready FastAPI versioning library with comprehensive deprecation management and backward compatibility
Project description
FastAPI Versioner
A production-ready FastAPI versioning library with comprehensive deprecation management and backward compatibility.
🚀 Features
- Multiple Versioning Strategies: URL path, headers, query parameters, and Accept header versioning
- Deprecation Management: Comprehensive deprecation warnings with sunset dates and migration guidance
- Backward Compatibility: Automatic version negotiation and fallback mechanisms
- Type Safety: Full type hints and validation throughout
- Flexible Configuration: Extensive configuration options for different use cases
- Automatic Documentation: Integration with FastAPI's OpenAPI documentation
- Version Discovery: Built-in endpoint for API version information
📦 Installation
pip install fastapi-versioner
Or with uv:
uv add fastapi-versioner
🎯 Quick Start
⚠️ IMPORTANT: You must create
VersionedFastAPIAFTER defining all your routes with@versiondecorators. This is crucial for proper route processing.
Basic Usage
from fastapi import FastAPI
from fastapi_versioner import VersionedFastAPI, version
app = FastAPI()
# Define your routes FIRST
@app.get("/users")
@version("1.0")
def get_users_v1():
return {"users": [], "version": "1.0"}
@app.get("/users")
@version("2.0")
def get_users_v2():
return {"users": [], "total": 0, "version": "2.0"}
# Create VersionedFastAPI AFTER defining routes
versioned_app = VersionedFastAPI(app)
# Run the versioned app
if __name__ == "__main__":
import uvicorn
uvicorn.run(versioned_app.app, host="0.0.0.0", port=8000)
With Deprecation
from datetime import datetime
from fastapi_versioner import deprecated, WarningLevel
@app.get("/users")
@version("1.0")
@deprecated(
sunset_date=datetime(2024, 12, 31),
warning_level=WarningLevel.CRITICAL,
replacement="/v2/users",
reason="Use v2 for better performance"
)
def get_users_v1_deprecated():
return {"users": [], "version": "1.0"}
# Create VersionedFastAPI AFTER defining routes
versioned_app = VersionedFastAPI(app)
Advanced Configuration
from fastapi_versioner import VersioningConfig, VersionFormat
# Define routes first
@app.get("/users")
@version("1.0")
def get_users_v1():
return {"users": [], "version": "1.0"}
@app.get("/users")
@version("2.0")
def get_users_v2():
return {"users": [], "version": "2.0"}
# Configure versioning
config = VersioningConfig(
default_version="2.0",
version_format=VersionFormat.SEMANTIC,
strategies=["url_path", "header"],
enable_deprecation_warnings=True,
include_version_headers=True
)
# Create VersionedFastAPI AFTER defining routes
versioned_app = VersionedFastAPI(app, config=config)
🔧 Versioning Strategies
URL Path Versioning
# Requests: GET /v1/users, GET /v2/users
from fastapi_versioner import URLPathVersioning
strategy = URLPathVersioning(prefix="v")
Header Versioning
# Requests with header: X-API-Version: 1.0
from fastapi_versioner import HeaderVersioning
strategy = HeaderVersioning(header_name="X-API-Version")
Query Parameter Versioning
# Requests: GET /users?version=1.0
from fastapi_versioner import QueryParameterVersioning
strategy = QueryParameterVersioning(param_name="version")
Accept Header Versioning
# Requests with header: Accept: application/json;version=1.0
from fastapi_versioner import AcceptHeaderVersioning
strategy = AcceptHeaderVersioning(version_param="version")
📋 API Endpoints
When you use FastAPI Versioner, the following endpoints are automatically available:
GET /versions- Version discovery endpoint- Your versioned endpoints (e.g.,
/v1/users,/v2/users)
🔄 Version Negotiation
FastAPI Versioner supports intelligent version negotiation:
config = VersioningConfig(
negotiation_strategy=NegotiationStrategy.CLOSEST_COMPATIBLE,
auto_fallback=True,
compatibility_matrix=your_compatibility_matrix
)
⚠️ Deprecation Management
Comprehensive deprecation features:
@deprecated(
sunset_date=datetime(2024, 12, 31),
warning_level=WarningLevel.CRITICAL,
replacement="/v2/endpoint",
migration_guide="https://docs.example.com/migration",
reason="Performance improvements in v2"
)
🧪 Testing
Run the test suite:
uv run python -m pytest tests/ -v
Run with coverage:
uv run python -m pytest tests/ --cov=src/fastapi_versioner --cov-report=html
🛠️ Development Setup
Prerequisites
- Python 3.8+
- uv (recommended) or pip
Setup
- Clone the repository:
git clone https://github.com/tonlls/fastapi-versioner.git
cd fastapi-versioner
- Install dependencies:
uv sync --all-extras --dev
- Install pre-commit hooks (recommended):
uv run pre-commit install
Pre-commit Hooks
This project uses pre-commit hooks to ensure code quality. The hooks will automatically run before each commit and:
- Fix code formatting with Ruff
- Check for linting issues
- Run type checking with MyPy
- Perform security scanning with Bandit
- Run tests to ensure nothing is broken
What happens when you commit:
git add .
git commit -m "Your changes"
# Pre-commit automatically runs:
# ✓ Ruff formatting and linting
# ✓ MyPy type checking
# ✓ Bandit security scan
# ✓ Test suite
# If any check fails, the commit is blocked until fixed
Manual pre-commit run:
# Run all hooks on all files
uv run pre-commit run --all-files
# Run specific hook
uv run pre-commit run ruff --all-files
Code Quality Tools
- Ruff: Fast Python linter and formatter
- MyPy: Static type checking
- Bandit: Security vulnerability scanner
- Pytest: Testing framework with coverage
Development Workflow
- Create a feature branch
- Make your changes
- Run tests:
uv run pytest - Commit (pre-commit hooks will run automatically)
- Push and create a pull request
📚 Examples
Check out the examples/ directory for complete working examples:
examples/basic/- Basic versioning setupexamples/advanced/- Advanced configurationexamples/migration/- Migration scenariosexamples/strategies/- Different versioning strategies
All examples follow the correct pattern of creating VersionedFastAPI after defining routes.
🏗️ Architecture
FastAPI Versioner is built with a modular architecture:
- Core:
VersionedFastAPImain class and middleware - Strategies: Pluggable versioning strategies
- Types: Comprehensive type system for versions and configuration
- Decorators: Easy-to-use decorators for marking versions and deprecation
- Compatibility: Version negotiation and backward compatibility
🤝 Contributing
Contributions are welcome! Please read our Contributing Guide for details.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
🎉 Acknowledgments
- Built for the FastAPI ecosystem
- Inspired by Django REST Framework's versioning
- Designed for production use cases
FastAPI Versioner - Making API versioning simple, powerful, and production-ready.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_versioner-0.1.0.tar.gz.
File metadata
- Download URL: fastapi_versioner-0.1.0.tar.gz
- Upload date:
- Size: 73.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c08d9fe13b9ca0b0041c782af02a13ce7a5b59a79718e1b7a76fd8b83f0ad9f7
|
|
| MD5 |
c1201f8cdbeccaed4add61c375e64ea6
|
|
| BLAKE2b-256 |
9871dd835b555b09e29f87138a86534d10341310ad5361dd9f8814c63a3f7247
|
File details
Details for the file fastapi_versioner-0.1.0-py3-none-any.whl.
File metadata
- Download URL: fastapi_versioner-0.1.0-py3-none-any.whl
- Upload date:
- Size: 47.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2c065af4dfe150f82c72f49bae1c319058700fdc690e96dd815db3fa2081f0d2
|
|
| MD5 |
bc298f78630103307f36ef2603247ff1
|
|
| BLAKE2b-256 |
ca3165331e2c746ef9917c47480de81384ddfb7fdd24d24695f35076ae723af1
|