Jump to

  • Quickstarts
  • API reference
  • Webhook events
  • Error codes
  • SDKs

Resources

Python SDK

Call the Trovacast API from Python 3.11 or later with a sync or asyncio client, typed request bodies, retries and idempotency keys built in, and webhook verification.

trovacast is the typed client for the Trovacast API on Python 3.11 or later, with one runtime dependency, httpx. It is generated from the same OpenAPI contract as the API reference, and it follows the same retry, idempotency and error rules as the Node.js SDK.

Install

Install from PyPI, once it is published (bash)
python3 -m pip install trovacast

The changelog lists what changed in each version.

Create a client

Create a client (python)
import os

from trovacast import Trovacast

client = Trovacast(api_key=os.environ["TROVACAST_API_KEY"])

me = client.get_me()
print(me["kind"], me["scopes"])

get_me answers the key's kind and scopes. An api_key that does not look like a Trovacast key (tc_…) raises ValueError before anything is sent. Call client.close() when you are done, or use the client as a context manager (with Trovacast(...) as client:), to release its connections. The samples below use this client.

OptionDefaultWhat it does
api_keyRequiredA project or integration key: tc_live_…, or tc_test_… for test mode.
base_url"https://api.trovacast.com"The API origin. A trailing /v1 is accepted.
timeout30.0The timeout of each attempt in seconds, applied to connecting, reading, writing and waiting for a pooled connection.
max_retries2Retries after the first attempt, for a failure that is safe to retry. From 0 to 10.
initial_retry_delay0.5The first backoff step, in seconds. It doubles on each retry, with jitter.
max_retry_delay8.0The largest backoff step, in seconds.
max_retry_after60.0The longest Retry-After the client waits out, in seconds. A longer one is raised at once with retry_after set, so your job queue can reschedule.
user_agentNoneYour own product token, such as my-app/1.0, put before trovacast-sdk-python/<version> in the User-Agent.
http_clientNoneYour own httpx.Client (an httpx.AsyncClient for AsyncTrovacast), for proxies or mounts. You close it: close() leaves it open.
organizationNoneFor an integration key: the organization every call acts for, sent as Trovacast-Organization. Make one client per organization.

Every argument is keyword-only. Each method also takes idempotency_key= on writes and timeout= for that one call.

Make a request

Methods are the operationIds in snake_case: create_message, get_whatsapp_consent, list_sms_senders. OPERATION_METHODS maps every operationId to its method. A method takes its path and query parameters in snake_case and body when the operation has one, and returns the parsed body (None for a 204). Bodies are dicts with the API's own camelCase field names, typed as TypedDicts.

Send a WhatsApp template (python)
contact = client.upsert_contact(
    body={"phone": "+919876543210", "displayName": "Aarav"},
    idempotency_key="order-1001-contact",
)

message = client.create_message(
    body={
        "type": "template",
        "contactId": contact["id"],
        "template": {"name": "order_confirmation", "language": "en"},
        "variables": {"var1": "Aarav", "var2": "#1001"},
    },
    idempotency_key="order-1001-confirmation",
)
print(message["id"], message["status"])  # queued; later statuses arrive by webhook

idempotency_key names the write's key. A key built from your order id makes the send safe to repeat: a retried job gets the first answer back instead of sending twice. The WhatsApp template quickstart walks through the whole send.

Query arguments are sent under the API's names, so contact_id goes out as contactId. None is left out, a bool is sent as true or false, a timezone-aware datetime as ISO 8601 (a naive one is refused), and a list as one pair per item. The request and response types are in trovacast.types, named after their schemas without Public and Dto: Contact, Message, CreateMessage.

Read the response details

client.with_response has the same methods and returns an ApiResponse with data, status, headers, request_id, idempotency_key, idempotent_replayed and rate_limit. Use it when the status matters, as when an upsert tells a new contact (201) from an existing one (200).

Tell a new contact from an existing one (python)
response = client.with_response.upsert_contact(body={"phone": "+919876543210"})
contact, created = response.data, response.status == 201
print(contact["id"], created, response.request_id, response.rate_limit)

rate_limit is a RateLimitInfo(limit, remaining, reset_seconds) read from the X-RateLimit-* headers, or None when they are absent. rate_limit_of(headers) and parse_retry_after(value) are exported for your own use. See Rate limits.

Paginate

paginate yields every item of a list and fetches the next page only when your loop needs it; pages yields one page at a time. Both take the method name and that method's keyword arguments, and a cursor= you pass is where the walk starts.

Every message, then every page of contacts (python)
for message in client.paginate("list_messages", contact_id="CONTACT_ID"):
    print(message["id"], message["status"])

for page in client.pages("list_contacts", limit=100):
    print(len(page["data"]), page["nextCursor"])

The walk ends when nextCursor is null. It raises TypeError if the API answers something that is not a page, or the same cursor twice. See Pagination.

Use asyncio

AsyncTrovacast takes the same options and has the same methods as async def functions, with async for pagination, async with and aclose(). Its http_client is an httpx.AsyncClient.

The async client (python)
import asyncio
import os

from trovacast import AsyncTrovacast


async def main() -> None:
    async with AsyncTrovacast(api_key=os.environ["TROVACAST_API_KEY"]) as client:
        contact = await client.get_contact(contact_id="CONTACT_ID")
        async for message in client.paginate("list_messages", contact_id=contact["id"]):
            print(message["id"], message["status"])


asyncio.run(main())

Handle errors

Every failed call raises TrovacastApiError. Branch on its code, which is stable; the message is written for people, and str(error) returns it.

Handle a missing contact (python)
from trovacast import TrovacastApiError

try:
    contact = client.get_contact(contact_id="CONTACT_ID")
    print(contact["id"])
except TrovacastApiError as error:
    if error.is_not_found:
        print("no such contact", error.request_id)
    else:
        raise
AttributeWhat it holds
statusThe HTTP status, or 0 when no response arrived.
codeThe API's code, such as CONSENT_REQUIRED or API_KEY_SCOPE_MISSING, or one the SDK sets when no answer arrived or it could not be read: NETWORK_ERROR, TIMEOUT, INVALID_RESPONSE or UNEXPECTED_REDIRECT. A proxy's answer without a code is HTTP_<status>.
messageReadable text. Validation messages are joined with ; .
request_idThe API's request id. Quote it to support.
doc_urlThe code's entry in the error reference, or None.
retryableWhether repeating the call later is safe and could succeed. The client has already spent its own retries when you see it.
retry_afterThe server's Retry-After in seconds, or None.
idempotency_keyThe key the write was sent with. Reuse it when you retry.
idempotent_replayedTrue when the API answered from its idempotency store: the outcome for that key is fixed.
bodyThe parsed error body, with any extra fields the API sent.
is_not_foundTrue for a 404.

TROVACAST_ERROR_CODES lists every code this release knows, and is_known_error_code(code) tells a known code from a newer one: read a code you do not know by its status. The error never holds the API key, a request body or a URL, and the underlying httpx exception is never chained to it, so it is safe to log. It survives pickling, for task queues and multiprocessing.

Retries and idempotency

Every write (POST, PUT, PATCH or DELETE) carries an Idempotency-Key. By default the client mints a fresh UUID for each call and sends the same key on every retry of that call, so a retry whose first attempt landed gets the stored answer instead of running twice. Pass your own idempotency_key, 1 to 255 visible ASCII characters, to make a write safe across processes and restarts too. idempotency_key=False sends none, and that write is then never retried.

  • Retried: a timeout, a network error, 429, 500, 502, 503, 504 and 409 IDEMPOTENCY_KEY_IN_FLIGHT, up to max_retries times, with exponential backoff and jitter (0.5 s, doubling, at most 8 s) and never sooner than Retry-After. Only reads, and writes that carry a key, are retried.
  • Raised at once: a Retry-After longer than max_retry_after, with retry_after set for your job queue, and any error the API replayed from its idempotency store.
  • Replayed errors: when idempotent_replayed is True, every retry with that key gets the same answer. Read the resource to see whether the first attempt took effect, and only if it did not, send the write again with a new key.
  • A redirect is never followed, so the key never travels to another URL.

Idempotency explains what the API stores against a key, and for how long.

Verify webhooks

Verify the raw body before you parse it. construct_webhook_event checks the Trovacast-Signature header against every secret you pass, in constant time and within 300 seconds, and returns the event. A delivery that fails raises TrovacastWebhookError, whose reason says why: SIGNATURE_MISSING, TIMESTAMP_OUT_OF_TOLERANCE, SIGNATURE_MISMATCH or PAYLOAD_INVALID. Answer it with 400. trovacast.webhooks needs only the standard library.

Verify a delivery in Flask (python)
import os

from flask import Flask, request
from trovacast.webhooks import TrovacastWebhookError, construct_webhook_event

app = Flask(__name__)


@app.post("/trovacast/webhook")
def trovacast_webhook():
    try:
        event = construct_webhook_event(
            payload=request.get_data(),  # the exact bytes
            header=request.headers.get("Trovacast-Signature"),
            secrets=[os.environ["TROVACAST_WEBHOOK_SECRET"]],
        )
    except TrovacastWebhookError:
        return "", 400
    # Deliveries arrive at least once: deduplicate on event["id"].
    if event["type"] == "message.delivered":
        print(event["data"]["message"]["id"])
    return "", 204

In FastAPI or Starlette the raw body is await request.body(), and in Django it is request.body. verify_webhook_signature(payload, header, secrets, tolerance_seconds=300, now=None) returns True or False and raises only for a programming error. parse_webhook_event(payload) parses a body you have already verified, and in your own tests create_webhook_signature_header(payload, secret) signs a delivery. The scheme itself is described under Webhooks.

Rotate a secret

After you rotate an endpoint's secret, every delivery for the next 24 hours carries a second v1 signature made with the previous secret. A delivery is genuine when any signature matches any secret you pass, so list both while you deploy the new one: secrets=[current, previous]. Passing no secret, or an empty one, raises TypeError or ValueError, since anyone could compute a signature with an empty key.

Build call flows

CallFlowBuilder builds a stored call flow and AnswerBuilder the document an answer URL returns, one chained method per verb. to_dict() checks the document as the API will and raises CallFlowValidationError, a ValueError whose issues give each problem's path and message. trovacast.flows needs only the standard library, so an answer-URL server can use it without the client.

Build an IVR and store it (python)
from trovacast.flows import CallFlowBuilder, node, say

flow = CallFlowBuilder(start="main")
flow.node("main").menu(
    prompt=[say("Press 1 for sales, 2 for support.")],
    options={"1": node("sales"), "2": node("support")},
)
flow.node("sales").connect({"number": "+918031150000"})
flow.node("support").say("Please call back in office hours.").hangup()

created = client.create_call_flow(body={"name": "Main menu", "definition": flow.to_dict()})
print(created["id"])

Keyword arguments are snake_case and are sent as the API's fields, so on_timeout goes out as onTimeout. The set and switch verbs are the methods set_ and switch_. validate() returns a CallFlowValidationResult(ok, issues) instead of raising, and validate_call_flow(document) checks a document built any other way.

Next steps