Skip to main content

spoo

The official Python SDK for the spoo.me URL shortener API.

CI PyPI Python Codecov License

from spoo import SpooClient

client = SpooClient()
print(client.shorten("https://example.com").short_url)
  • Sync and async clients with the same API
  • Fully typed: every response is a Pydantic model, py.typed included
  • Sign in with Spoo (PKCE device auth) with automatic token refresh
  • Automatic, idempotency-aware retries
  • Auto-pagination for list endpoints
  • Two runtime dependencies: httpx and pydantic

Migrating from py_spoo_url? See MIGRATION.md.

Install

pip install spoo
# or
uv add spoo

Requires Python 3.10+.

Authentication

client = SpooClient()                    # reads SPOO_API_KEY, else anonymous
client = SpooClient(api_key="spoo_...")  # explicit API key
client = SpooClient(api_key="")          # force anonymous even with env set
client = SpooClient(bearer_token=...)    # a JWT, or a callable returning one

Anonymous clients work under anonymous limits. Create API keys from your spoo.me dashboard. Self-hosting? Point base_url (or SPOO_BASE_URL) at your instance's /api/v1.

Note that the base URL is a security boundary: every request, credential, and server-suggested filename flows through whatever it points at. Prefer the explicit base_url argument in anything security-sensitive, since the environment variable can redirect a whole process without any call site showing it.

Async is the same surface with AsyncSpooClient, await, and async for.

Links

from spoo import SpooClient, LinkFilter, LinkStatus, SortBy

client = SpooClient(api_key="spoo_...")

url = client.links.create(
    "https://example.com",
    alias="mylink",
    password="Secret@123",
    max_clicks=500,
    expire_after="2026-12-31T00:00:00",
    block_bots=True,
    private_stats=True,
)

# Check availability first if you want a precise reason
check = client.links.check_alias("mylink")
if not check.available:
    print(check.reason)  # taken | format | length | reserved | emoji_policy

# Fetch one link by id, or by its address
link = client.links.get(url.id)
preview = client.links.preview("mylink")   # public: destination, status, protection
link = client.links.get_by_alias("mylink")                    # your base domain
link = client.links.get_by_alias("mylink", domain="links.acme.com")

# Iterate everything (auto-pagination), or one filtered page
for item in client.links.list(sort_by=SortBy.TOTAL_CLICKS):
    print(item.alias, item.total_clicks)
page = client.links.list_page(filter=LinkFilter(status=LinkStatus.ACTIVE, search="docs"))

# Update, toggle, delete
client.links.update(url.id, long_url="https://example.com/new", max_clicks=0)
client.links.set_status(url.id, LinkStatus.INACTIVE)
client.links.delete(url.id)

Bulk operations

Up to 100 ids per call; results are reported per item instead of throwing:

result = client.links.bulk_set_status(ids, LinkStatus.INACTIVE)
print(result.summary.succeeded, result.summary.failed)
for row in result.results:
    if not row.ok:
        print(row.id, row.error_code)

client.links.bulk_delete(ids)
client.links.bulk_set_expiry(ids, "2027-01-01T00:00:00")   # None clears
client.links.bulk_set_domain(ids, "links.acme.com")        # None = default

Emoji aliases

url = client.shorten("https://example.com", alias="🚀🔥")       # pick your own
url = client.shorten("https://example.com", alias_type="emoji")  # auto-generate

The SDK validates emoji aliases before sending, against the server's own accepted catalogue (fetched once per client and cached). The catalogue is available directly for building pickers:

emoji_set = client.links.emoji_set()   # ~1170 entries with names and groups

Claim links

Anonymous creates return a one-time claim_token. After the user signs in, the token proves they created the link and transfers ownership, stats included:

anon_url = SpooClient(api_key="").shorten("https://example.com")

result = client.links.claim(anon_url.id, anon_url.claim_token)
print(result.status)   # claimed | already_yours | invalid

client.links.claim_many([(id1, token1), (id2, token2)])   # up to 16

Statistics

Account-wide analytics (requires authentication):

from spoo import GroupBy, Metric, StatsFilter

stats = client.stats.query(
    start_date="2026-07-01",
    end_date="2026-08-19",
    group_by=[GroupBy.TIME, GroupBy.COUNTRY, GroupBy.DEVICE, GroupBy.UTM_SOURCE],
    metrics=[Metric.CLICKS, Metric.UNIQUE_CLICKS],
    timezone="Asia/Kolkata",
    filters=StatsFilter(country=["IN", "US"], utm_campaign=["launch"]),
)
print(stats.summary.total_clicks)
for row in stats.metrics["clicks_by_country"]:   # "{metric}_by_{dimension}"
    print(row)

For a single link you own:

stats = client.stats.for_link(url.id, group_by=[GroupBy.TIME])

Public per-link stats work without authentication. Password-protected links take the password in a POST body, never in the URL:

public = client.stats.public("mylink")
public = client.stats.public("mylink", password="Secret@123")

Exports

Same parameters as query(), in csv, xlsx, json, or xml. The return value is bytes plus the server's suggested filename and content_type:

from pathlib import Path
from spoo import ExportFormat

data = client.stats.export(ExportFormat.CSV, start_date="2026-07-01")
Path(data.filename or "report.csv").write_bytes(data)   # server names the file

link_data = client.stats.export_link(url.id, ExportFormat.XLSX)
Path(link_data.filename or "link.xlsx").write_bytes(link_data)

Sign in with Spoo

For connected apps: the PKCE device-auth flow gets you user-scoped tokens without handling passwords. Your app must be registered with spoo.me.

client = SpooClient()
pkce = client.oauth.generate_pkce()
state = client.oauth.generate_state()

# 1. Send the user to the consent page
print(client.oauth.authorization_url("my-app", code_challenge=pkce.challenge, state=state))

# 2. Your redirect URI receives code + state; verify state, then exchange
tokens = client.oauth.exchange_code(code, pkce.verifier)
print(tokens.user.email)

# 3. A provider keeps the session fresh (refresh tokens rotate: persist them)
provider = client.oauth.token_provider(tokens, on_refresh=save_to_disk)
user_client = SpooClient(bearer_token=provider)
print(user_client.me().plan)

When the refresh token itself is rejected, calls raise SessionExpiredError: send the user through the flow again. See examples/sign_in_with_spoo.py for the full loop.

Error handling

Errors map to typed exceptions carrying the backend error code:

Status Exception
400 / 422 ValidationError
401 AuthenticationError
403 ForbiddenError
404 NotFoundError
409 ConflictError
410 GoneError
413 PayloadTooLargeError
429 RateLimitError (retry_after, limit, remaining, reset)
451 ContentBlockedError (the link was taken down for safety)
503 ServiceUnavailableError
other 5xx InternalServerError

Network failures raise APIConnectionError / APITimeoutError; a rejected refresh token raises SessionExpiredError. All of them subclass SpooError.

from spoo import RateLimitError, ValidationError

try:
    client.shorten("https://example.com", alias="taken")
except ValidationError as e:
    print(e.error_code, e.message)
except RateLimitError as e:
    print(f"limited, window resets at {e.reset}")

Scope

The SDK covers the data plane a third-party integration builds against: links (create, manage, bulk, claim, emoji aliases), analytics (account, per-link, public, exports), the public preview, and Sign in with Spoo plus the read-only identity check.

Deliberately out of scope: API key management, account and profile lifecycle, /contact, /health, and all legacy (pre-v1) endpoints. Feature-gated surfaces (custom domains management, webhooks, geo rules, meta tags) are not wrapped while they are not generally available, except the domain parameters which pass through.

Method Endpoint
shorten, links.create POST /api/v1/shorten
links.check_alias GET /api/v1/shorten/check-alias
links.list, links.list_page GET /api/v1/urls
links.get GET /api/v1/urls/{url_id}
links.get_by_alias GET /api/v1/urls/{domain}/{alias}
links.update, links.set_status, links.delete PATCH/DELETE /api/v1/urls/{url_id}
links.delete_all DELETE /api/v1/urls?domain=
links.claim, links.claim_many POST /api/v1/urls/claim
links.bulk_* POST /api/v1/urls/bulk/{delete,status,expiry,domain}
links.preview GET /api/v1/public/preview/{short_code}
links.emoji_set GET /api/v1/emoji-set
stats.query, stats.for_link GET /api/v1/stats, /api/v1/stats/links/{url_id}
stats.public GET/POST /api/v1/public/stats/{short_code}
stats.export, stats.export_link GET /api/v1/export, /api/v1/export/links/{url_id}
oauth.* /auth/device/{token,refresh}
me GET /auth/me

For anything not listed, client.request(method, path, params=, json=) is the supported escape hatch: it applies the client's auth, retries, and error mapping, and returns the parsed JSON. If you need it, the surface has a gap worth filing.

Retries and configuration

Retries (default 2) honor Retry-After and back off exponentially with jitter. GET/PUT/DELETE retry on 408/429/5xx and network failures; POST/PATCH retry only on 429 and 503, where the server provably did no work.

client = SpooClient(
    api_key="spoo_...",
    base_url="https://your-instance/api/v1",
    timeout=30.0,
    max_retries=3,
    default_headers={"X-Request-ID": "..."},
)

Every request carries an X-Spoo-Client: sdk-py/<version> tag; override it via default_headers if you are building a product on top and want traffic attributed to it.

Note on custom domains: domain= parameters work end to end, but custom domains are currently in a limited beta on spoo.me, so most accounts will see 403 until it opens up.

Examples

Runnable scripts in examples/: quickstart, async usage, analytics, link management, claim links, emoji aliases, and Sign in with Spoo.

Development

uv sync
uv run pytest
uv run ruff check src/ tests/ examples/
uv run mypy --strict src/spoo/

Versioning

Response models tolerate new fields (extra="allow"), so additive API changes never break an installed version. Breaking changes bump the major version.

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spoo-1.3.0.tar.gz (38.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spoo-1.3.0-py3-none-any.whl (36.0 kB view details)

Uploaded Python 3

File details

Details for the file spoo-1.3.0.tar.gz.

File metadata

  • Download URL: spoo-1.3.0.tar.gz
  • Upload date:
  • Size: 38.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for spoo-1.3.0.tar.gz
Algorithm Hash digest
SHA256 96a1a3ba522074e3d9f1c34ab3b1941c89348b2f1f498b607ae027a1e7fdff4f
MD5 00c2b51bfaef36b2c1a33c2378111454
BLAKE2b-256 a8d8400087c6faf3d889d141f513fbdead852140632d16c57efd454700081fa5

See more details on using hashes here.

Provenance

The following attestation bundles were made for spoo-1.3.0.tar.gz:

Publisher: python-publish.yml on spoo-me/spoo-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spoo-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: spoo-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 36.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for spoo-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 11257f307b561d50334b0cdf8fb705e557df7cb4430edd3de9d177847703e614
MD5 fef823a26af46edf09b2b3f15e82bfc1
BLAKE2b-256 5d34dc42f1c6ca085b15521e1586134dfed2914ebbd48da577179d932029a984

See more details on using hashes here.

Provenance

The following attestation bundles were made for spoo-1.3.0-py3-none-any.whl:

Publisher: python-publish.yml on spoo-me/spoo-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

1.5.0

2 files

1.4.0

2 files

This release

1.3.0 This release

2 files

1.2.0

2 files

1.1.0

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page