The repository or configuration that created this release differ from a previous release. View details.
fastapi-canon
Canon adds shared error handling, typed streams, WebSocket APIs and client generation to FastAPI. Public error definitions are shared across HTTP, SSE and WebSocket RPC, exported contracts, and generated Python and TypeScript clients.
Contents
- What Canon handles
- Install
- Shared error handling
- HTTP, SSE and WebSocket clients
- Instrument application boundaries
- Check contracts in CI
- Learn more
What Canon handles
- HTTP, SSE and WebSockets: typed operations, event streams and RPC methods, with generated Python and TypeScript clients.
- Public errors: map domain exceptions once, declare them with
raises=, and carry the contract into HTTP RFC 9457 Problem Details, streams and SDKs. - Static checks and code generation: find missing error mappings and declarations, report incomplete analysis, and catch generated-client drift in CI.
- Application composition: features contribute routers, Dishka providers and lifespans; composition owns installation and cleanup.
- Instrumentation: declare observed services and ports at the feature boundary without adding telemetry annotations to business logic.
Generated SDKs do not depend on Canon. Python clients use Pydantic, an HTTP client
and, for RPC, websockets; TypeScript clients use fetch/DOM APIs.
See client generation for supported operations
and target requirements.
Install
uv add "fastapi-canon[sse,websockets]"
uv add --dev "fastapi-canon[codegen]"
For HTTP-only applications, use uv add fastapi-canon. The base includes
FastAPI, Pydantic and Dishka. Python 3.12–3.14 is supported.
The current published release is 0.15.0. See the upgrade guide and tested compatibility. Upgrade servers and regenerated clients together.
This checkout prepares 0.16.0, which is not yet published. Main-branch examples target its APIs; see the 0.16.0 upgrade guide.
Shared error handling
Keep domain exceptions in ordinary Python. Define their public representation
once with Error, then declare it on operations with raises=:
from fastapi import FastAPI
from fastapi_canon import APIRouter, Composition, Error, ErrorOptions, Feature
class ProjectMissing(Exception):
pass
project_missing = Error(
ProjectMissing,
status=404,
code="project_missing",
title="Project not found",
detail="Choose another project.",
)
router = APIRouter()
@router.get(
"/projects/{project_id}",
operation_id="projects.get",
raises=[project_missing],
)
async def get_project(project_id: int) -> dict[str, int]:
if project_id == 0:
raise ProjectMissing()
return {"id": project_id}
app = Composition(
features=(Feature(name="projects", routers=[router]),),
errors=ErrorOptions(type_base="https://api.example.com/problems"),
).build(FastAPI())
GET /projects/0 returns a 404 application/problem+json response following
RFC 9457, with type https://api.example.com/problems/project_missing and code
project_missing. OpenAPI documents the same problem. Exception messages stay
private by default; the declared detail is public.
Reuse the same project_missing object in @router.sse(..., raises=[...]) and
@channel.method(raises=[...]). There is one domain-to-public-error mapping:
| Where the failure occurs | How it reaches the client |
|---|---|
| HTTP request or SSE admission | HTTP Problem Details response |
| During an SSE stream | Terminal canon.problem event |
| WebSocket RPC method | Problem data in the JSON-RPC error envelope |
These bindings preserve the problem's type, code and declared public fields.
HTTP status is included in HTTP problems and omitted from SSE terminal and RPC
problems. RFC 9457 defines HTTP Problem Details; the stream and RPC bindings are
Canon conventions.
Generated SDKs expose these failures through a shared ProblemError:
from api_client import ProblemError
try:
project = await client.projects.get(project_id=0)
except ProblemError as error:
print(error.problem.type)
This client excerpt runs inside an async function with a generated client. The quickstart shows the complete server and SDK setup; shared problems covers typed extensions, validation failures and safe internal errors.
HTTP, SSE and WebSocket clients
Declare a typed stream on Canon's APIRouter:
from collections.abc import AsyncIterator
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi_canon import APIRouter, Composition, Feature
class Token(BaseModel):
text: str
router = APIRouter()
@router.sse("/tokens", operation_id="generation.tokens")
async def tokens() -> AsyncIterator[Token]:
yield Token(text="Hello")
yield Token(text=" world")
app = Composition(
features=(Feature(name="generation", routers=[router]),),
).build(FastAPI())
With a codegen configuration pointing at your app, generate both clients. The SSE-only app exports only its OpenAPI contract:
uv run fastapi-canon generate
TypeScript:
import { createClient } from "./generated";
const client = createClient({ baseUrl: "http://localhost:8000" });
try {
for await (const token of client.generation.tokens()) {
console.log(token.text);
}
} finally {
await client.close();
}
Python, inside an async function:
from api_client import ApiClient
async with ApiClient("http://localhost:8000") as client:
async for token in client.generation.tokens():
print(token.text)
The event model becomes the client's item type. Canon handles framing, decoding
and explicit stream completion. Declared terminal problems raise ProblemError;
an unexpected EOF raises TransportError.
The same SDK can expose HTTP lookups and WebSocket RPC calls such as
client.projects.get(...) and client.projects.cancel(...), with shared models
and public problem errors. See the complete walkthrough.
Instrument application boundaries
Add the otel extra and declare the services or ports to observe:
from fastapi_canon import Feature
from fastapi_canon.integrations.opentelemetry import instrument
tasks = Feature(
name="tasks",
routers=(router,),
providers=(TaskProvider,),
instrumentation=instrument(
TaskRepository,
TaskService,
expected=(TaskNotFound,),
),
)
This excerpt uses your application's router, provider and service types.
Enable it with Composition(..., telemetry=Telemetry(...)). Canon observes
declared async methods through Dishka and adds port spans alongside HTTP
telemetry. Your application owns SDK providers and exporters.
See the instrumentation guide for a complete setup.
Check contracts in CI
uv run fastapi-canon check errors src --strict --require-complete
uv run fastapi-canon generate --check --diff
The static checker follows supported application calls and dependencies; it reports unresolved paths rather than claiming complete coverage. Use it alongside runtime tests. The generator checks exported contracts and client files for drift.
Learn more
Start with the quickstart, then choose a task guide or a runnable example.
Optional integrations also include WebRTC media sessions, MCP and database resources.
For coding agents, install the bundled
build-canon-backend skill
from your application project:
uv run fastapi-canon skill install
For updates and destination options, see the skill installation guide. Contributor commands and repository architecture live in contributing.
Metadata
Release files for fastapi-canon 0.16.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Change of provenance
The repository or configuration that created these release files differ from that of a previous release.
We recommend inspecting the repository and configuration before proceeding. View details.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_canon-0.16.0.tar.gz | 442.6 kB | With provenance | Details for fastapi_canon-0.16.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_canon-0.16.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_canon-0.16.0-py3-none-any.whl |
Total release size: 971.8 kB
Release files / fastapi_canon-0.16.0.tar.gz
Change of provenance
This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.
We recommend inspecting the repository and configuration before proceeding. View details.
| Download URL | fastapi_canon-0.16.0.tar.gz |
|---|---|
| Size | 442.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d409bf92135d05d986837b2ff911964c5ec35347fdaedf375c503a1d2be40a7c
|
|
BLAKE2b-256 checksum How to use checksums |
5ec320ffff5ba1f019eefd6ad8baeba0f31d5011f158b4bb40d4bb01c84f48d8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logRelease files / fastapi_canon-0.16.0-py3-none-any.whl
Change of provenance
This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.
We recommend inspecting the repository and configuration before proceeding. View details.
| Download URL | fastapi_canon-0.16.0-py3-none-any.whl |
|---|---|
| Size | 529.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e24607ba935650fd8dbe4b412882590b56f1aabbae5c23ae7f579a69f49bcc1e
|
|
BLAKE2b-256 checksum How to use checksums |
e185c932a01126aeeecb3b3ce99b63768aa1afed3dd9fab6d50f143163f2bb40
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logSecurity for fastapi-canon 0.16.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Change of provenance
The repository and configuration that created this release differ from a previous release.
While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.
Repository
- Removed 0.15.0 github.com/mathisarends/fastapi_canon
- Added 0.16.0 github.com/mathisarends/fastapi-canon
Attestation for fastapi_canon-0.16.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.