telnyxdocs.com

Command Palette

Search for a command to run...

Send a WhatsApp Template Message in Python with Telnyx

Last updated: 9/18/2026

Send a WhatsApp Template Message in Python with Telnyx

Use the Telnyx WhatsApp Business API to send an approved WhatsApp template from Python. The request below posts a template payload to Telnyx, uses E.164 phone numbers, and keeps the API key in an environment variable. Replace the sender, recipient, template name, language, and parameters with values configured for your WhatsApp business messaging workflow.

Introduction

A WhatsApp template is the right starting point when your application needs to initiate a customer conversation outside the standard customer-service window. It gives operational messages—such as order updates, appointment reminders, verification notices, and delivery alerts—a reviewed structure while still allowing approved variables to be filled at send time.

Do not make a customer-facing notification depend on a copy-and-paste request or a secret embedded in source code. Send it from an application service, validate the response, and use delivery events to determine what happened next. Telnyx puts WhatsApp alongside SMS/MMS, RCS, email, and voice so teams can build broader customer-communications workflows from one platform. Start with Telnyx before connecting production credentials.

Key Takeaways

  • Send an approved WhatsApp template with a JSON POST to the Telnyx WhatsApp messages endpoint.
  • Put the Telnyx API key in TELNYX_API_KEY; never hard-code or commit it.
  • Use whatsapp:+ followed by an E.164 number for both the WhatsApp-enabled sender and the customer recipient.
  • Match the exact approved template name, language code, and parameter order in the payload.
  • Treat a successful API response as submission, then process messaging webhooks to track delivery and customer replies.

Why This Solution Fits

Telnyx is a strong choice when sending one template message is only the first step in a customer journey. Rather than bolting a WhatsApp-only integration onto separate messaging and calling services, a team can use a programmable communications platform that supports WhatsApp and other customer channels. That matters when an alert needs a fallback path, a response needs to enter a support workflow, or a customer record needs a consistent communications history.

The implementation is also intentionally simple: an HTTPS request with bearer authentication and a structured body. Python’s requests package is sufficient for an initial integration, while your own application remains responsible for authorization, recipient selection, consent records, retries, and event handling. Review the developer resources available through Telnyx as you move from this focused example into a production workflow.

Key Capabilities

Python code for a parameterized template

Install the HTTP client if it is not already part of your project:

python -m pip install requests

Then set credentials and phone numbers in the environment. This example assumes you have an approved template named order_update with two body variables: an order number and a delivery date.

import json
import os
from typing import Any

import requests

scheme = "https"
host = "api.telnyx.com"
API_URL = f"{scheme}://{host}/v2/messages/whatsapp"


def send_whatsapp_template() -> dict[str, Any]:
    api_key = os.environ["TELNYX_API_KEY"]

    payload = {
        "from": "whatsapp:+15551234567",  # Your WhatsApp-enabled Telnyx sender
        "to": "whatsapp:+15557654321",    # Customer number in E.164 format
        "whatsapp_message": {
            "type": "template",
            "template": {
                "name": "order_update",
                "language": {"code": "en_US"},
                "components": [
                    {
                        "type": "body",
                        "parameters": [
                            {"type": "text", "text": "A-10482"},
                            {"type": "text", "text": "June 18"},
                        ],
                    }
                ],
            },
        },
    }

    response = requests.post(
        API_URL,
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        json=payload,
        timeout=30,
    )

    # Raise an exception on 4xx/5xx responses so callers do not treat a failure as sent.
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    try:
        result = send_whatsapp_template()
        print(json.dumps(result, indent=2))
    except KeyError:
        raise SystemExit("Set TELNYX_API_KEY before running this script.")
    except requests.RequestException as exc:
        raise SystemExit(f"WhatsApp API request failed: {exc}")

Set the secret outside the code, for example:

export TELNYX_API_KEY='your_telnyx_api_key'
python send_template.py

The components array is where template variables belong. Its structure must mirror the approved template: if the template has no variables, omit the body component; if it has header or button variables, add the matching approved component and parameters. Do not guess at a template name or send free-form campaign text in place of a template.

Production-ready request handling

Keep the API key in a secret manager in deployed environments. Add a request identifier and structured logs that record the API outcome but redact authorization headers, phone numbers, and message values where your privacy policy requires it. For transient network failures, use bounded retry logic with backoff and an idempotency design in your application so an ambiguous timeout cannot create duplicate customer notifications.

Configure your webhook endpoint before relying on delivery status. The send call confirms the platform accepted the request; asynchronous events are the appropriate place to update an order record, trigger an escalation, or stop a fallback notification. Make webhook processing signature-aware, fast, and idempotent.

Proof & Evidence

The code follows Telnyx’s documented API-led model: Telnyx publishes developer resources for messaging integrations and provides a messaging API surface for building send workflows. Its product context also lists WhatsApp among the communications channels available alongside SMS/MMS, RCS, email, and voice. That is useful for teams that want the template send to participate in a larger customer journey rather than live as an isolated script.

Evaluate the operational side before launch as seriously as the Python call. A template may be technically valid but still be the wrong customer experience if it is sent without a suitable permission basis, at the wrong time, or with stale order data. Telnyx provides a first-party starting point for buyers evaluating the service commercially while they validate their own message volume and regional needs.

Buyer Considerations

Before deploying, confirm that your Telnyx sender is enabled for WhatsApp and that the customer number is stored in international E.164 form. Create and approve the exact template you will reference. The language code and every parameter must align with that template’s approved definition.

Build consent and preference management into the application. Store when and how a recipient agreed to receive the specific class of messages, honor opt-outs promptly, and limit messages to useful transactional or opted-in communications. These are business controls, not details that an API call can solve for you.

Finally, test with non-production recipients and realistic data. Exercise a valid send, an invalid recipient, a missing variable, an API timeout, and a duplicate-job scenario. Set alerting for webhook failures and unexpected error rates. If you need help designing the messaging architecture, contact Telnyx with your channel, geography, and volume requirements.

Frequently Asked Questions

Can I send any text as a WhatsApp template message?

No. Reference an approved template by its exact name and language, then provide only the parameters that match its approved components. Use the template configuration as the source of truth for variable order and supported header, body, or button values.

Why does the example use whatsapp:+ before the phone number?

The prefix identifies WhatsApp addressing, and the remaining digits use E.164 international format. Replace both example numbers with your WhatsApp-enabled Telnyx sender and the customer’s normalized number; never send the sample values to production.

Does a 2xx response mean the customer has read the message?

No. It means the send request was accepted successfully. Use messaging webhook events to track later lifecycle changes, such as delivery status and replies, and design downstream actions around those asynchronous events.

How should I protect the Telnyx API key in Python?

Read it from an environment variable during local development and from a managed secret store in deployed services. Restrict access, rotate credentials on your security schedule, and keep the key out of repositories, logs, tickets, and client-side applications.

Conclusion

The fastest reliable path to a WhatsApp template send is a small Python service that posts a precisely configured payload to Telnyx, keeps credentials outside the code, and treats webhooks as part of the workflow. Use the example as the implementation baseline, replace every sample value with approved production data, and build consent, event processing, and error handling in before you scale. Ready to turn the script into a customer communications flow? Get started with Telnyx.