honkio
The official Python SDK for HonkIO: Canadian SMS and email, with CASL built in. Data is stored in Canada (ca-central-1).
- Python 3.10 or newer; one dependency, httpx
- A synchronous client (
Honkio) and an asynchronous one (AsyncHonkio) with the same resources and arguments - Errors are exceptions; every API error is a subclass of
honkio.ApiError - Typed (
py.typed); responses are plain dicts described byTypedDicts, importable fromhonkio.types(from honkio.types import Message) - Retries what waiting fixes (a number's per-minute sending rate, the carrier asking to slow down), with an idempotency key so a retried send never goes out twice
Install
pip install honkio
Quickstart
Create a key in the dashboard under API Keys, Create key (https://honkio.ca/dashboard/keys); the full key is shown once, right after you create it. Start with a test key (mk_test_...): nothing is delivered or charged.
Send an SMS:
from honkio import Honkio
client = Honkio() # reads HONKIO_API_KEY
message = client.messages.send(
from_="+1416XXXXXXX", # one of your HonkIO numbers
to="+1613XXXXXXX", # a Canadian number you hold consent for
body="Hello from HonkIO!",
idempotency_key="order-1042",
)
print(message["id"], message["status"])
Send an email:
sent = client.emails.send(
from_="Acme <hello@yourdomain.ca>", # a verified sending domain
to="sam@example.com",
subject="Welcome",
html="<p>Hello!</p>",
idempotency_key="welcome-sam",
)
print(sent["id"])
The same calls, asynchronously:
import asyncio
from honkio import AsyncHonkio
async def main() -> None:
async with AsyncHonkio() as client:
message = await client.messages.send(from_="+1416XXXXXXX", to="+1613XXXXXXX", body="Hi")
print(message["id"])
asyncio.run(main())
Honkio() with no argument reads HONKIO_API_KEY and raises InvalidArgumentError if neither is set. Options: Honkio(api_key, base_url="https://api.honkio.ca", timeout=30.0, http_client=None, max_retries=2, max_retry_delay=60.0); see Retries. Pass your own httpx.Client (or httpx.AsyncClient) as http_client for proxies, mTLS or tests; the SDK then leaves closing it to you, and the timeout is the one you configured on it (timeout= applies only to a client the SDK builds). A client the SDK built is closed by client.close() (await client.aclose()), or by leaving a with (async with) block.
Arguments
Every call takes keyword-only arguments named like the API's own (snake_case) fields. from is a Python keyword, so it is from_ and is sent as from. A typo is a TypeError, not a silently ignored field. Ids come first, positionally: client.domains.remove("dom_1").
An optional argument you leave out is not sent (its default is honkio.NOT_GIVEN). Pass None to send an explicit JSON null, which clears a nullable field: client.domains.update("dom_1", open_tracking=None) restores the platform default, client.templates.update("welcome", from_address=None) clears the template's sender. In a query string None is omitted like NOT_GIVEN. Dicts you pass (variables, headers, template objects) are sent exactly as you wrote them. Query lists repeat the key.
Datetimes: pass a timezone-aware datetime (or an ISO 8601 string). It is sent in UTC with a Z suffix, so datetime(2026, 10, 15, 9, 0, tzinfo=ZoneInfo("America/Toronto")) goes out as 2026-10-15T13:00:00Z. A naive datetime raises InvalidArgumentError before anything is sent. The two date-only filters of messages.list (date_from, date_to) and last_transaction_date on consents take a date or a YYYY-MM-DD string and are sent as YYYY-MM-DD (a timezone-aware datetime there is converted to its UTC date).
Errors
from honkio import ApiError, UnavailableForLegalReasonsError, UnprocessableEntityError, APITimeoutError
try:
client.messages.send(from_="+1416XXXXXXX", to="+1613XXXXXXX", body="Hi")
except UnavailableForLegalReasonsError as e: # HTTP 451
print(e.code, e.message) # NO_CONSENT, CONSENT_EXPIRED, OPT_OUT_BLOCKED
except UnprocessableEntityError as e: # HTTP 422
print(e.code, e.message) # NON_CANADIAN_NUMBER, ...
except ApiError as e:
print(e.status_code, e.code, e.details)
except APITimeoutError:
... # retried already; the send may or may not have gone through: see Retries
| Exception | When |
|---|---|
ApiError (.code, .message, .status_code, .details) |
the API answered with an error; subclasses by status: BadRequestError 400, AuthenticationError 401, PaymentRequiredError 402, PermissionDeniedError 403, NotFoundError 404, ConflictError 409, UnprocessableEntityError 422, RateLimitError 429, UnavailableForLegalReasonsError 451, InternalServerError 5xx |
APIConnectionError, APITimeoutError |
no response arrived (DNS, refused connection, 30 s timeout) |
InvalidArgumentError (also a ValueError) |
refused before anything was sent: an id that is empty, . or .., a consent call that named both or neither subject, a naive datetime, an empty api_key, a webhook check with a missing secret |
InvalidSignatureError |
a webhook delivery could not be verified |
HonkioError |
the base of all of the above |
Every ApiError pickles (for task queues and multiprocessing). A 3xx answer (the SDK does not follow redirects) is an ApiError whose message and details["location"] carry the Location header; check base_url.
details is the API's details when it sent one, such as {"attempts_remaining": 2} on VERIFICATION_INVALID_CODE. Otherwise it holds whatever the API sent beside the error envelope. A body that is not JSON (a proxy error page, say) is ApiError with code application_error.
The general codes (authentication, permissions, balance, validation, rate limits) and every SMS and email code are listed at https://honkio.ca/docs/errors.
Retries
The client sends a call again when the API refused it only because it should wait:
| Code | Retried |
|---|---|
NUMBER_RATE_LIMITED (429) |
always: the sending number already has a minute of message segments waiting at the carrier (a local number sends 10 segments a minute) |
CARRIER_THROTTLED (503) |
always: the carrier asked HonkIO to slow down and did not take the message; nothing was charged |
CARRIER_UNAVAILABLE (503) |
always: the carrier could not be reached; nothing was sent or charged |
RATE_LIMITED (429) |
on a GET or a send with an idempotency key. Elsewhere it can be the route's own limit, such as one verification start per recipient a minute, where a repeat would send again |
APIConnectionError, APITimeoutError |
on a GET or a send with an idempotency key: the request may have reached the API |
Each retry waits as long as the API's Retry-After header (seconds, or an HTTP date to wait until) or details["retry_after_seconds"] says, or backs off exponentially with jitter when it says nothing. By default a call is retried at most 2 times, and a wait longer than 60 seconds is not waited out: the exception is raised at once. When retrying does not help, the last exception is raised, the same as without retries. AsyncHonkio waits with asyncio.sleep, so other tasks keep running.
client = Honkio(max_retries=4, max_retry_delay=30)
no_retries = Honkio(max_retries=0)
Never retried: CARRIER_TIMEOUT (the message may have gone out: check its status with messages.get before sending again), DAILY_LIMIT_REACHED, FANOUT_LIMIT_REACHED, RECIPIENT_RATE_LIMITED, SENDING_PAUSED, NUMBER_QUEUE_FULL, SCHEDULED_LIMIT_REACHED, and every validation, consent or authentication error.
A local number sends 10 message segments a minute, so a burst bigger than that is spread out at that pace: each refusal says how long until there is room (about 6 seconds per segment waiting). For a list, send to a contact group or pace your sends; for real volume, use a verified toll-free number. Do not spread one list across several numbers to go faster: carriers treat that as snowshoeing and it breaks the acceptable use policy.
Send limit and number queues
messages.send returns a SentMessage: the message plus estimated_send_at, when the carrier should start sending it, from the segments already waiting on the sending number (None in test mode and on a retry that returned an earlier send). send_limit.get() shows the rest before a burst: the daily cap and what is left of it, the per-recipient caps, probation, any pause, past volume requests, and number_queues, each number's carrier queue.
limits = client.send_limit.get()
print(limits["remaining"], "of", limits["daily_limit"], "left today")
for queue in limits["number_queues"]:
# parts_per_minute is 10 for a local number; clears_at is None when nothing is waiting.
print(queue["phone_number"], queue["queued_parts"], queue["parts_per_minute"], queue["clears_at"])
Scheduled SMS
messages.send(..., scheduled_at=...) takes a timezone-aware datetime or an ISO 8601 string, 1 minute to 30 days ahead. The message comes back SCHEDULED with scheduled_at and is charged now. Every check runs again when it is due: a recipient who opted out since, a revoked key, a suspended number or account fails it (refunded, message.failed), while a sending limit, a pause, or the carrier throttling it or being unreachable holds it and it is tried again until it can go. It must go out by expires_at= (only with scheduled_at, 1 minute to 24 hours after it; by default scheduled_at plus 24 hours): one that cannot fails with error_code SCHEDULED_SEND_EXPIRED, refunded, with message.failed. Until then messages.update(id, scheduled_at=..., expires_at=...) moves it (expires_at=None resets the deadline to the default; left out, a stored one is kept while it still fits the new time) and messages.cancel(id) cancels it and refunds the charge (MESSAGE_NOT_SCHEDULED once it has gone out). Events: message.rescheduled, message.cancelled.
Templates
A template holds a part for each channel you send it on (email, sms, push), in English, French or both. templates makes and edits any template, including an SMS-only or French one. email_templates (deprecated) keeps the older email-only shape for templates with an email part.
client.templates.create(
name="Sign-in code",
alias="signin-code",
default_language="en",
variables=[{"key": "code"}],
parts={
"en": {"sms": {"text": "Your Acme code: {{ code }}"}},
"fr": {"sms": {"text": "Votre code Acme : {{ code }}"}},
},
)
client.templates.publish("signin-code") # live keys only; a test key sends the draft
client.messages.send(
from_="+1416XXXXXXX", to="+1613XXXXXXX", template="signin-code", variables={"code": "123456"}, language="fr"
)
A send in a language uses that language's part for the channel, else the default language's. On update, each part you name in parts= replaces that part, None removes it, and parts you leave out are kept; parts={"fr": None} removes every French part. publish, rollback and remove need a live key.
Idempotency
messages.send, emails.send and batch.send always send an Idempotency-Key header: yours when you pass idempotency_key=, otherwise a generated UUID that stays the same on each retry of that call. The API answers a repeated key with the original result, so a retry can never send or charge twice.
The generated key covers only the client's own retries. If your code sends again after an exception (a task queue running a job again, say), pass your own key, derived from what is being sent (an order id), so the API recognises the repeat.
Webhooks
Check a delivery's signature before you trust it. Pass the raw request body exactly as received, before any JSON parsing:
from honkio import verify_webhook, InvalidSignatureError
def handle(request): # a Flask-style request
try:
event = verify_webhook(request.get_data(), request.headers, WEBHOOK_SECRET)
except InvalidSignatureError:
return "bad signature", 400
if event["type"] == "message.delivered":
...
return "", 204
verify_webhook(raw_body, headers, secret, *, tolerance_seconds=300) takes a str or bytes body and any mapping of headers, or any object with .items() such as Flask/Werkzeug request.headers (names are matched case-insensitively; a list value uses its first item; a list of tuples is refused with InvalidArgumentError). It returns the parsed event, raises InvalidSignatureError for anything about the signature, the timestamp (more than 300 seconds old) or the body, and InvalidArgumentError for bad input such as a body already parsed into a dict. client.webhooks.verify(...) is the same function. On AsyncHonkio it is still a plain function, not awaitable: call it without await. honkio.WEBHOOK_EVENTS lists every event a webhook can subscribe to.
HonkIO Auth
HonkIO Auth is hosted, passwordless sign-in for your app. Its full API reference, with every field and error, is at honkio.ca/docs/auth/api.
Manage apps with client.auth_apps (a key with the auth_apps permission; users, sessions, sign-ins and exports need auth_users; organizations, memberships, roles and invitations need auth_organizations). AsyncHonkio has the same methods, awaited.
app = client.auth_apps.create(
hostname="login.yourdomain.ca", name="Acme", redirect_uris=["https://app.yourdomain.ca/callback"]
)
# Publish app["dns_records"] (a TXT and a CNAME to edge.signin.honkio.ca), then:
client.auth_apps.verify_domain(app["id"])
client.auth_apps. |
Methods |
|---|---|
| (the app) | create, list, get, update (a hostname sent on its own moves the app to a new hostname once it is proven), cancel_hostname_change, remove, rotate_secret, verify_domain, upload_logo, remove_logo |
security |
get, update, summary |
blocklist |
list, add, remove |
plan |
get, change, cancel_scheduled, costs, usage |
sign_in_policy |
get, update |
organizations |
list, create, get, update, remove |
memberships |
list, add, get, update, remove |
roles |
list, put (create or update; create and update are aliases), remove |
invitations |
list, create, get, revoke |
users |
list, get, update, block, unblock, remove, remove_likely_bots (an auth_users:bulk_delete step-up per call), sessions, sign_ins, passkeys, remove_passkey |
sessions |
revoke |
sign_ins |
list |
exports |
create (needs a step-up token), get, latest (the newest export; with an auth_users:export step-up token, a fresh download link for the key that requested it), download (bytes; single use, within 15 minutes) |
A user's passkeys are public metadata only (never the key). Removing one tells the user at their email address and ends their sessions:
for passkey in client.auth_apps.users.passkeys(app_id, user_id)["data"]:
if not passkey["usable"]: # made under a passkey scope the app no longer uses
client.auth_apps.users.remove_passkey(app_id, user_id, passkey["id"])
Sign users in with any OpenID Connect library (the issuer is https://<your hostname>), then keep their session with honkio.auth (pip install "honkio[auth]", or honkio[fastapi] / honkio[flask]):
from honkio.auth import HonkioAuth, SessionCookie
from honkio.auth.flask import current_session, init_session, login_required, write_session
auth = HonkioAuth("https://login.yourdomain.ca", CLIENT_ID, CLIENT_SECRET)
cookie = SessionCookie(SESSION_SECRET) # 32+ characters
init_session(app, auth, cookie) # loads, refreshes and rewrites the sealed cookie
# In your sign-in callback, after your OIDC library exchanged the code:
session = auth.session_from_tokens(tokens, nonce=nonce)
write_session(response, cookie, session)
@app.get("/account")
@login_required(redirect_to="/sign-in")
def account():
return current_session().claims
verify_id_tokenandverify_access_tokencheck the ES256 signature against the app's keys (cached, and kept while HonkIO can't be reached), the issuer, the audience, the expiry and the token type, and raiseTokenVerificationError(with acode) otherwise. A token for another app, or an access token passed as an ID token, is refused.refresh_session(session)refreshes the access token when it has under a minute left. If HonkIO can't be reached (network error, timeout, 5xx), the user stays signed in for up to 24 hours past the access token's expiry (status"unavailable"). If HonkIO refuses the refresh (the session was revoked, the user blocked or deleted, or removed from the organization), the session ends at once (status"ended"). A 408 or 429 keeps the session for that request only. Requests carrying the same session in one process share one refresh while it runs, and requests still carrying the old session get the new one for 2 seconds after it, because a refresh token works once and reusing it ends the session. After that, a replayed old refresh token goes to HonkIO, whose reuse detection ends the session.- The Flask and FastAPI helpers mark every response that sets or clears the session cookie
Cache-Control: private, no-store, so a CDN or shared cache never hands one user's session to another. - FastAPI:
AsyncHonkioAuthwithhonkio.auth.fastapi.HonkioBearer(Bearer access tokens) andHonkioSessionDependency(the sealed cookie). Flask:require_access_token,init_session,login_required. - Sign-out:
auth.revoke(session.refresh_token)(it also forgets the session in this process), clear the cookie, and send the browser toauth.logout_url(id_token_hint=session.id_token, post_logout_redirect_uri=...). - The sealed cookie's format is the Node SDK's, so a Node and a Python service can share it.
Resources
client. |
Methods |
|---|---|
messages |
send (returns a SentMessage, with estimated_send_at), get, list, update, cancel |
phone_numbers |
area_codes, search, provision, list, get, release |
verify |
start, check, get, list. A test key sends nothing; the verification's test_code is the code that completes it (None on a live one) |
consents |
create, list, record_batch, check, revoke (the last two take exactly one of phone_number or email_address) |
consent_batches |
list, get |
opt_in_confirmations |
send, list |
webhooks |
create, list, get, update, remove, deliveries, dead_letters, replay, discard, reactivate, rotate_secret, verify |
emails |
send, get, list, update, cancel |
emails.received |
list, address, set_address_enabled, get, raw, attachment, simulate |
batch |
send (a list of emails, or recipients= for one message to many) |
domains |
create, get, list, update, verify, remove |
suppressions |
create, list, remove |
templates |
Templates with email, SMS and push parts in English and French (/v1/templates): create, get, list, update, publish, rollback, versions, remove; see Templates |
email_templates |
Deprecated: use templates. The email-only shape (/v1/email-templates) of the templates that have an email part, with the same methods |
toll_free_verifications |
options, create, update, submit, cancel, get, list |
business_verification |
get, save, submit |
auto_topup |
get |
send_limit |
get |
pricing |
get: current prices in CAD cents (message_cost_cents, verification_cost_cents, number rent and fees; email and push in millicents) |
topup_cap_requests |
create, list |
emails.received.raw and emails.received.attachment return bytes. A call that answers 204 (the deletes) returns None.
Full API reference: https://honkio.ca/docs/api. SDK guide: https://honkio.ca/docs/sdk.
Development
uv venv && uv pip install -e '.[dev]'
ruff check . && mypy --strict src && pytest
python scripts/generate_types.py # after web/generated/openapi.json changes
Inside the monorepo, the test suite reads web/generated/openapi.json (and the API source) and fails when a route or keyword argument the SDK uses is not in the spec, when WEBHOOK_EVENTS differs from the API's list, or when src/honkio/_types.py is stale. Those tests skip when run from a checkout without the monorepo.
License
MIT
Metadata
Release files for honkio 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| honkio-0.6.0.tar.gz | 76.5 kB | Without provenance | Details for honkio-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| honkio-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for honkio-0.6.0-py3-none-any.whl |
Total release size: 169.6 kB
Release files / honkio-0.6.0.tar.gz
| Download URL | honkio-0.6.0.tar.gz |
|---|---|
| Size | 76.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8082a08d7355e41b812c04ec3141acd3b19cb4122fdabda8ad7e0c232b7c1645
|
|
BLAKE2b-256 checksum How to use checksums |
bcdd00c36cf623e973e6246e436fe5fcd131dd91e8febedfa373fd0a95496337
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / honkio-0.6.0-py3-none-any.whl
| Download URL | honkio-0.6.0-py3-none-any.whl |
|---|---|
| Size | 93.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4fc367121582298822f2a6a26a634533309bdb692081706a7e7e122a1eef964b
|
|
BLAKE2b-256 checksum How to use checksums |
7a34d0b2ba54c71b2d58a67c24b606d734803c37619cad2a861b66bc6f142a05
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for honkio 0.6.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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A 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.