- What is ActivityPub?
- What is Pubby?
- Installation
- Quick Start
- Publishing Content
- Rendering Plain-Text Content
- Key Management
- Custom Storage
- Configuration Reference
- Rendering Interactions
- Rate Limiting
- Document Caching
- Interaction Callbacks
- Strict Attribution
- Signature Verification
- API
- Tests
- Development
- License
A general-purpose Python library to add ActivityPub federation support to your website.
What is ActivityPub?
ActivityPub is a W3C standard for decentralized social networking. Servers exchange JSON-LD activities (posts, likes, follows, boosts) over HTTP, enabling federation across platforms like Mastodon, Pleroma, Misskey, and others. It's the protocol that powers the Fediverse.
What is Pubby?
Pubby is a framework-agnostic library that handles the ActivityPub plumbing so you can focus on your app:
- Inbox processing — receive and dispatch Follow, Like, Announce, Create, Update, Delete activities
- Outbox delivery — concurrent fan-out to follower inboxes with retry and shared-inbox deduplication
- HTTP Signatures — sign outgoing requests and verify incoming ones
(draft-cavage, using
cryptographydirectly — nohttpsigdependency) - Discovery — WebFinger and NodeInfo 2.1 endpoints
- Interaction storage — followers, interactions, activities, actor cache
- Framework adapters — Flask, FastAPI, Tornado
- Storage adapters — SQLAlchemy (any supported database) and file-based JSON
- Rust SDK — the same ActivityPub core available as the
pubby-sdkcrate (see Rust SDK)
Installation
Base install:
pip install pubby
With extras:
pip install "pubby[db,flask]" # SQLAlchemy + Flask
pip install "pubby[db,fastapi]" # SQLAlchemy + FastAPI
pip install "pubby[db,tornado]" # SQLAlchemy + Tornado
Available extras: db, flask, fastapi, tornado.
Rust SDK
The Rust implementation lives under src/rust and is published to
crates.io as pubby-sdk:
[dependencies]
pubby-sdk = "0.3"
Cargo features: db (SQLite storage via rusqlite), redis
(Redis-backed document store), axum (web framework adapter),
async/tokio (async support). The crate is framework-agnostic at its
core — pubby_sdk::server::dispatch maps
(method, path, query, headers, body) to a plain response so any Rust
web framework can integrate; the axum feature ships a ready-made
Router (activitypub_router/mastodon_router).
The SDK mirrors the Python API (ActivityPubHandler, inbox/outbox
processing, HTTP Signatures, WebFinger/NodeInfo, followers/interactions
storage, the Mastodon-compatible API, quote support) with idiomatic Rust
types. See src/rust/README.md for usage.
Quick Start
Flask
pip install "pubby[db,flask]"
from flask import Flask
from pubby import ActivityPubHandler
from pubby.crypto import generate_rsa_keypair, export_private_key_pem
from pubby.storage.adapters.db import init_db_storage
from pubby.server.adapters.flask import bind_activitypub
app = Flask(__name__)
storage = init_db_storage("sqlite:////tmp/pubby.db")
# Generate a keypair (persist this — don't regenerate on restart!)
private_key, _ = generate_rsa_keypair()
handler = ActivityPubHandler(
storage=storage,
actor_config={
"base_url": "https://example.com",
"username": "blog",
"name": "My Blog",
"summary": "A blog with ActivityPub support",
},
private_key=private_key,
)
bind_activitypub(app, handler)
app.run()
FastAPI
pip install "pubby[db,fastapi]"
from fastapi import FastAPI
from pubby import ActivityPubHandler
from pubby.crypto import generate_rsa_keypair
from pubby.storage.adapters.db import init_db_storage
from pubby.server.adapters.fastapi import bind_activitypub
app = FastAPI()
storage = init_db_storage("sqlite:////tmp/pubby.db")
private_key, _ = generate_rsa_keypair()
handler = ActivityPubHandler(
storage=storage,
actor_config={
"base_url": "https://example.com",
"username": "blog",
"name": "My Blog",
"summary": "A blog with ActivityPub support",
},
private_key=private_key,
)
bind_activitypub(app, handler)
Tornado
pip install "pubby[db,tornado]"
from tornado.web import Application
from tornado.ioloop import IOLoop
from pubby import ActivityPubHandler
from pubby.crypto import generate_rsa_keypair
from pubby.storage.adapters.db import init_db_storage
from pubby.server.adapters.tornado import bind_activitypub
app = Application()
storage = init_db_storage("sqlite:////tmp/pubby.db")
private_key, _ = generate_rsa_keypair()
handler = ActivityPubHandler(
storage=storage,
actor_config={
"base_url": "https://example.com",
"username": "blog",
"name": "My Blog",
"summary": "A blog with ActivityPub support",
},
private_key=private_key,
)
bind_activitypub(app, handler)
app.listen(8000)
IOLoop.current().start()
Registered Routes
All adapters register the same endpoints:
| Method | Path | Description |
|---|---|---|
GET |
/.well-known/webfinger |
WebFinger discovery |
GET |
/.well-known/nodeinfo |
NodeInfo discovery |
GET |
/nodeinfo/2.1 |
NodeInfo 2.1 document |
GET |
/ap/actor |
Actor profile (JSON-LD) |
POST |
/ap/inbox |
Receive activities |
GET |
/ap/outbox |
Outbox collection |
GET |
/ap/followers |
Followers collection |
GET |
/ap/following |
Following collection |
The /ap prefix is configurable via the prefix parameter on bind_activitypub.
Mastodon-compatible API
Pubby ships a read-only subset of the Mastodon REST API so that Mastodon-compatible clients and crawlers can discover the instance, look up the actor, list published statuses, and inspect followers.
Call bind_mastodon_api alongside bind_activitypub:
from pubby.server.adapters.flask import bind_activitypub
from pubby.server.adapters.flask_mastodon import bind_mastodon_api
bind_activitypub(app, handler)
bind_mastodon_api(
app,
handler,
title="My Blog", # instance title (default: actor name)
description="A cool blog", # instance description (default: actor summary)
contact_email="me@example.com", # optional contact e-mail
software_name="MyApp", # shown in /api/v1/instance version string
software_version="1.0.0",
)
The same function is available for all three frameworks:
pubby.server.adapters.flask_mastodon.bind_mastodon_apipubby.server.adapters.fastapi_mastodon.bind_mastodon_apipubby.server.adapters.tornado_mastodon.bind_mastodon_api
Mastodon API Routes
| Method | Path | Description |
|---|---|---|
GET |
/api/v1/instance |
Instance metadata (v1) |
GET |
/api/v2/instance |
Instance metadata (v2) |
GET |
/api/v1/instance/peers |
Peer domains from followers |
GET |
/api/v1/accounts/lookup |
Resolve acct:user@domain → Account |
GET |
/api/v1/accounts/:id |
Account by ID ("1" = local actor) |
GET |
/api/v1/accounts/:id/statuses |
Paginated statuses for account |
GET |
/api/v1/accounts/:id/followers |
Paginated followers list |
GET |
/api/v1/statuses/:id |
Single status by ID |
GET |
/nodeinfo/2.0 |
NodeInfo 2.0 alias |
GET |
/nodeinfo/2.0.json |
NodeInfo 2.0 .json alias |
GET |
/nodeinfo/2.1.json |
NodeInfo 2.1 .json alias |
bind_mastodon_api Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
app |
framework app | required | Flask / FastAPI / Tornado application |
handler |
ActivityPubHandler |
required | The handler instance |
title |
str |
actor name | Instance title |
description |
str |
actor summary | Instance description |
contact_email |
str |
"" |
Contact e-mail |
software_name |
str |
handler's software_name |
Software name in version string |
software_version |
str |
handler's software_version |
Software version string |
Status & Account IDs
- The local actor always has account ID
"1". - Status IDs are URL-safe base64 encodings of the AP object URL, making them deterministic and reversible.
Publishing Content
Publish an article to all followers:
from pubby import Object
article = Object(
id="https://example.com/posts/hello-world",
type="Article",
name="Hello World",
content="<p>My first federated post!</p>",
url="https://example.com/posts/hello-world",
attributed_to="https://example.com/ap/actor",
)
handler.publish_object(article)
To update or delete:
# Update
handler.publish_object(updated_article, activity_type="Update")
# Delete
handler.publish_object(deleted_article, activity_type="Delete")
Delivery is concurrent (configurable via max_delivery_workers, default 10)
with automatic retry and exponential backoff on failure.
Custom Delivery
To route deliveries through your own task queue (Celery, RQ, …) instead of
the built-in thread pool, pass a deliver callable to the handler. Pubby
still stores the activity and computes the deduplicated inbox set — with
shared-inbox preference and instance allow/block filtering — then invokes
your callable once per inbox:
from pubby import ActivityPubHandler
def deliver(inbox_url, activity):
send_activity.delay(inbox_url, activity) # e.g. a Celery task
handler = ActivityPubHandler(
storage=storage,
actor_config={...},
private_key=private_key,
deliver=deliver,
)
Inside the task, pubby.deliver_activity performs a single signed POST and
returns the HTTP status code so your worker can apply its own retry policy:
from pubby import deliver_activity
@app.task(bind=True, max_retries=5)
def send_activity(self, inbox_url, activity):
status = deliver_activity(
activity,
inbox_url,
key_id=handler.key_id,
private_key=private_key,
)
if status == 429 or status >= 500:
raise self.retry(countdown=60)
deliver_activity never raises on 4xx/5xx responses — it returns the status
code. Network-level failures (connection errors, timeouts) still raise the
underlying requests exception. Applications that build a fully custom
fan-out can reuse pubby.collect_inboxes(followers) to get the same
shared-inbox-preferred, deduplicated inbox list publish() uses.
Rendering Plain-Text Content
pubby.content turns plain user text into safe ActivityPub HTML and Hashtag
tags. It is stdlib-only and independent of the inbound HTML sanitiser in
pubby.render.
Render a post and publish it:
from pubby import Object, build_hashtag_tags, render_post_html
hashtag_url = lambda name: f"https://example.com/tags/{name}"
rc = render_post_html(
"Hello fediverse! #intro https://example.com/about",
hashtag_url,
)
post = Object(
id="https://example.com/posts/1",
type="Note",
content=rc.html,
url="https://example.com/posts/1",
attributed_to="https://example.com/ap/actor",
tag=build_hashtag_tags(rc.hashtags, hashtag_url),
)
handler.publish_object(post)
For object dictionaries — e.g. Audio/Video payloads you build by hand —
set_object_content does the same in one call: it renders the text into
obj["content"] and appends any detected hashtags to obj["tag"],
deduplicating against tags you already set:
from pubby import set_object_content
obj = {
"type": "Audio",
"id": "https://example.com/tracks/1",
"tag": build_hashtag_tags(["jazz"], hashtag_url),
}
set_object_content(obj, "Live set #jazz #fusion", hashtag_url)
# obj["content"] holds rendered HTML; obj["tag"] now includes #fusion
For bios that should only linkify URLs, use render_bio_html on the summary
field:
from pubby import ActivityPubHandler, render_bio_html
handler = ActivityPubHandler(
storage=storage,
actor_config={
"base_url": "https://example.com",
"username": "blog",
"summary": render_bio_html("Find me at https://example.com/links."),
},
private_key=private_key,
)
See the Content Rendering API reference for the full list of helpers.
Key Management
Important: your RSA keypair is your server's identity. Persist it — if you regenerate it, other servers won't be able to verify your signatures.
The simplest option is ensure_private_key_file, which generates an RSA-2048
keypair and writes it with 0o600 permissions the first time, then reuses the
existing file on subsequent runs:
from pubby.crypto import ensure_private_key_file
handler = ActivityPubHandler(
storage=storage,
actor_config={...},
private_key_path=ensure_private_key_file("/var/lib/myapp/actor.pem"),
)
Or manage the keypair yourself:
from pubby.crypto import (
generate_rsa_keypair,
export_private_key_pem,
load_private_key,
)
# Generate once and save
private_key, public_key = generate_rsa_keypair()
pem = export_private_key_pem(private_key)
with open("/path/to/private_key.pem", "w") as f:
f.write(pem)
# Load on startup
handler = ActivityPubHandler(
storage=storage,
actor_config={...},
private_key_path="/path/to/private_key.pem",
)
Custom Storage
If you don't want to use SQLAlchemy or the file-based adapter, extend
ActivityPubStorage:
from pubby import ActivityPubStorage, Follower, Interaction
class MyStorage(ActivityPubStorage):
def store_follower(self, follower: Follower):
...
def remove_follower(self, actor_id: str, target_actor_id: str = ""):
...
def get_followers(self, actor_id: str | None = None) -> list[Follower]:
...
def get_followers_of_targets(self, target_ids: Collection[str]) -> list[Follower]:
... # Optional: default filters get_followers(); DB adapter uses IN
def store_interaction(self, interaction: Interaction):
...
def delete_interaction(self, source_actor_id: str, target_resource: str, interaction_type: str):
...
def get_interactions(self, target_resource: str | None = None, interaction_type: str | None = None) -> list[Interaction]:
...
def get_interactions_mentioning(self, actor_url: str, interaction_type: str | None = None) -> list[Interaction]:
... # Optional: returns interactions where actor_url is in mentioned_actors
def get_interaction_by_object_id(self, object_id: str, status: InteractionStatus = InteractionStatus.CONFIRMED) -> Interaction | None:
... # Optional: look up interaction by remote object URL
def store_activity(self, activity_id: str, activity_data: dict):
...
def get_activities(self, limit: int = 20, offset: int = 0) -> list[dict]:
...
def cache_remote_actor(self, actor_id: str, actor_data: dict):
...
def get_cached_actor(self, actor_id: str, max_age_seconds: int = 86400) -> dict | None:
...
handler = ActivityPubHandler(
storage=MyStorage(),
actor_config={...},
private_key=private_key,
)
Async Database URLs
DbActivityPubStorage is synchronous. If your application runs on an async
database stack, pass its URL to init_db_storage directly — known async
drivers are converted automatically (sqlite+aiosqlite → sqlite,
postgresql+asyncpg → postgresql+psycopg2):
storage = init_db_storage("sqlite+aiosqlite:////tmp/pubby.db")
Unknown async drivers raise ValueError. Extend or override the default
mapping with driver_map (e.g. for psycopg3):
storage = init_db_storage(
"postgresql+asyncpg://user:pass@db.example.com/mydb",
driver_map={"postgresql+asyncpg": "postgresql+psycopg"},
)
to_sync_url(url, driver_map=None) is also exported if you only need the
converted URL:
from pubby.storage.adapter
