Sanic Extensions
Sanic-Ext is a powerful extension package for the Sanic web framework, providing core functionality like OpenAPI documentation (Swagger UI, Redoc), dependency injection, request data validation, background tasks, and CORS handling. It aligns its major version numbers with Sanic releases (e.g., v25.12.0 for Sanic 23.12/24.12/25.12). The project releases new major versions annually, typically in December, with patch and minor updates in between.
Warnings
- breaking Sanic-Ext versions are tightly coupled with Sanic framework versions. For example, `sanic-ext==25.12.0` is intended for use with `sanic>=23.12,<26.0`. Using a significantly older or newer Sanic version with an incompatible `sanic-ext` version can lead to runtime errors or unexpected behavior.
- gotcha The behavior and capabilities of request data validation and OpenAPI schema generation have evolved across versions, especially with the introduction of `msgspec` support in `v23.12.0` and refinements to `pydantic`/`attrs` integration. Default type coercions or schema representations might differ slightly.
- gotcha Prior to `v25.12.0`, Sanic-Ext could experience `KeyErrors` in query parameter validation under certain conditions. Additionally, issues related to handler list mutation (when dynamically adding/removing handlers) were present.
- gotcha In versions prior to `v25.12.0`, the background logger might fail to remove unpickleable items, potentially leading to resource leaks or unexpected behavior in long-running applications that utilize background logging.
Install
-
pip install sanic-ext -
pip install sanic-ext[msgspec] -
pip install sanic-ext[pydantic]
Imports
- Extend
from sanic_ext import Extend
- Sanic
from sanic import Sanic
Quickstart
from sanic import Sanic
from sanic_ext import Extend
from typing import Optional
app = Sanic("My App with Sanic-Ext")
Extend(app)
@app.get("/")
async def hello_world(name: str = "World"):
# Sanic-Ext automatically injects query parameters based on type hints
return {"hello": name}
@app.post("/items")
async def create_item(item_id: int, description: Optional[str] = None):
# This demonstrates basic type-hinted injection for path/query parameters
return {"item_id": item_id, "description": description, "status": "created"}
if __name__ == "__main__":
# Run the Sanic application
# Sanic-Ext provides features like OpenAPI docs at /docs or /swagger
app.run(host="0.0.0.0", port=8000, debug=True)