Skip to content

Integrations

Twilio SDK: get started

Twilio core v2010 through typed application or agent clients

Use an ordinary App, or an Agent when the workload needs agent identity. Alter builds provider requests from a reviewed contract and applies the same connection authorization, policy, approvals, and audit records as raw requests.

Terminal window
npm install @alter-ai/sdk @alter-ai/twilio
# Python (installs core automatically)
pip install alter-sdk-twilio

The provider package includes only Twilio types and response schemas and pins its contract version.

Configure Twilio with its Account SID and required Auth Token, then create a grant for the application or end user. Alter composes the Basic credential and supplies it on requests. The Account SID also selects resources in native request paths; the Auth Token never belongs in operation input. This connection uses Basic authentication rather than OAuth scopes. Credentials are verified on first use because the composed credential has no template preflight endpoint.

import { App } from "@alter-ai/sdk";
import { TwilioIntegration } from "@alter-ai/twilio";
const app = new App({ apiKey: process.env.ALTER_API_KEY! });
try {
const client = new TwilioIntegration(app, { grantId: process.env.TWILIO_GRANT_ID! });
const result = await (await client.balance.fetchBalance({ path: { AccountSid: process.env.TWILIO_ACCOUNT_SID! } })).wait();
console.log(result.bodyJson());
} finally {
await app.close();
}
from alter_sdk import App
from alter_sdk_twilio import TwilioIntegration
async def first_call(api_key: str, grant_id: str, account_sid: str):
async with App(api_key=api_key) as app:
client = TwilioIntegration(app, {"grant_id": grant_id})
call = await client.balance.fetch_balance({"path": {"AccountSid": account_sid}})
result = await call.wait()
return result.body_json()

Contract 2026-11-17 contains 187 publishable operations from Twilio’s official core v2010 OpenAPI document. All 197 source operations are policy-cataloged; ten credential operations are excluded from the SDK. Other Twilio products, such as Verify and Conversations, are separate upstream documents and are outside this contract. The API reference links every operation to its complete input fields, response models, TypeScript and Python examples, and policy identity. Browse by resource under this provider’s API reference in the Integrations sidebar, or download the pinned OpenAPI specification. The Developer Portal provider view and alter integrations operations twilio --version 2026-11-17 also expose the schemas.

Generated calls pin the Alter contract version. Twilio’s own product, role, scope and subscription requirements still apply. There is no silent version fallback and no automatic write retry or pagination.

Terminal window
alter integrations execute twilio twilio.fetchbalance \
--version 2026-11-17 --grant "$TWILIO_GRANT_ID" --input '{"path":{"AccountSid":"AC00000000000000000000000000000000"}}' --wait

Arguments use native path, query, headers, and body containers. Array query parameters are sent the way the provider’s document declares them: one delimited value where it declares explode: false (or a pipe- or space-delimited style), repeated keys otherwise. SDK methods preserve provider field names, decimal lexemes and large integers as strings when necessary. HTTP 204 returns null / None from the typed decoder. Binary responses use bodyBytes() / body_bytes(); the CLI can save them with --output-file.

A policy rule can require approval for any operation. The call returns a pending approval; wait() resolves once the approver decides, and resume(approvalId) picks a pending approval up after a restart. Approval cards show the operation, its contract version and the request input the sensitivity review marked safe to display.

Pass native form fields inside body. Alter serializes them as application/x-www-form-urlencoded, preserving repeated array fields such as MediaUrl and JSON-encoding the payment connector’s Parameter object. Stream custom parameters such as Parameter1.Name remain literal flat keys. This contract has no multipart file upload operations. Media inputs are provider-fetched URLs, subject to the same destination policy and approval checks. The shared serialized-body limit applies.

Communication delivery and external callbacks carry send; buying or enabling recurring billable resources, including phone-number purchases, carries payment. Per-use CreateMessage and CreateCall carry send and write, without payment solely for metering. Account security, routing configuration and access changes carry admin. The generated reference shows each operation’s complete family set and projected fields, including recipients, destinations and account identifiers.

Account creation and retrieval can expose Auth Tokens. API/signing-key creation or deletion and SIP password setters also receive credential controls and are excluded from SDK methods. Raw calls remain named and refused by default unless an operator explicitly permits credential operations; the SIP password update refusal applies when Password is present. Narrow call tokens, validation codes, TURN credentials and signed add-on download links are not account-login credentials, but their responses are excluded from payload capture.

Payload capture follows the application’s setting. Reviewed personal, message, address, authentication and payment-connector fields are masked in approvals and captures; raw card data is refused by the shared guard. Twilio reports failed API requests through HTTP status codes. A failed asynchronous delivery recorded in a successfully fetched message is resource data, not a failed fetch. The add-on payload-data operation returns Twilio’s redirect response; inspect its status and headers without treating the signed download URL as ordinary log data.

The pinned official source, its hash, the generated methods and the policy mapping are checked together. Scheduled checks save upstream candidates and report additions, removals and schema changes; they never replace a published contract automatically. Existing contract versions remain available for installed SDKs and pending approvals.

Persist call.approvalId (TypeScript) or call.approval_id (Python), then construct a fresh provider client and call resume(savedId), followed by wait(). The stored approval selects the operation; this installed package verifies its provider and contract version before attaching the response validator. Mismatches raise ManagedOperationError, never silently decode using another contract. See persist-and-resume examples.

Policy operation fields also accept the published SDK function IDs listed by alter integrations operations twilio. Use when.operation for a json_match or conditional require_approval rule, or match.operations for content_match (including redaction and step-up). Conditional approval can also use when.match.operations with parameter conditions. alter policy simulate --operation <function-id> tests that exact function.

Managed calls carry a server-verified function identity. Alter still evaluates policy against the actual method, URL and body after building the request from the authorized connection. Endpoint, method and host restrictions still apply. This first managed SDK publication replaces the earlier Twilio catalog with reviewed operation, family and parameter labels. It removes 18 earlier CreateCall parameter projections and 12 CreateMessage projections; rules using those selectors must be updated to the published catalog. FetchAccount, ListAccount, UpdateAccount, DeleteKey and DeleteSigningKey are refused by default. CreateCall and UpdateCall expose Twiml as a policy selector: inline instructions can specify destinations independently of To and Url, so rules restricting those fields must also govern Twiml. A raw call can share an endpoint with several SDK functions and matches all of them; a function name never grants permission or bypasses existing restrictions.

For example, this rule requires approval for one function:

{
"effect": "require_approval",
"when": { "operation": "twilio.createmessage" },
"approval": { "approvers": ["reviewer@example.com"] }
}

Save it with alter policy rules create --app <app-id> --grant <grant-id> --type require_approval --body @rule.json, or select the function in the portal.

Report an issue with this page

Necessary

Required for sign-in, security, authorization, and remembering your choices.

Always active

Analytics

Helps us understand how our website, product, and documentation are used.

Performance diagnostics

Uses performance tracing and privacy-masked session replay to diagnose problems.

Advertising

Shares visits and sign-ups with Meta, Reddit, and X so we can measure which of our ads work.

You can change these choices at any time from Cookie settings.