Skip to content

Twilio WhatsApp API — Sending and Receiving WhatsApp Messages

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Twilio WhatsApp API. We cover key concepts, practical examples, and best practices to help you master this topic.

Twilio WhatsApp API allows businesses to send and receive WhatsApp messages using the same Twilio messaging infrastructure, with template-based messaging for proactive outreach and free-form messaging for customer replies.

What You'll Learn

  • How to set up the Twilio WhatsApp sandbox
  • How to send WhatsApp messages
  • How to handle incoming WhatsApp messages

Why It Matters

WhatsApp has 2+ billion users worldwide with higher open rates (98%) than email (20%) or SMS (90%). Twilio WhatsApp API lets you reach customers on their preferred messaging platform with rich media support (images, documents, buttons).

Real-World Use

DodaTech uses WhatsApp for: order confirmations with rich product images, delivery updates with tracking links, support conversations via WhatsApp Business, and appointment reminders. WhatsApp's 98% open rate ensures customers see these messages within minutes.

Sandbox Setup

from twilio.rest import Client

client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

def send_whatsapp_message(to_number, message_body):
    message = client.messages.create(
        body=message_body,
        from_='whatsapp:+14155238886',  # Twilio sandbox number
        to=f'whatsapp:{to_number}'
    )
    print(f"WhatsApp message sent: {message.sid}")
    return message.sid

# Join the sandbox first by texting "join <sandbox-code>"
# to the Twilio sandbox number via WhatsApp

send_whatsapp_message('+15559876543', 'Hello from DodaTech! Your order has been confirmed.')

Template-Based Messaging

def send_whatsapp_template(to_number, template_sid, template_data):
    """Send a pre-approved WhatsApp template"""
    message = client.messages.create(
        from_='whatsapp:+14155238886',
        to=f'whatsapp:{to_number}',
        content_sid=template_sid,  # Template SID from Twilio
        content_variables=json.dumps(template_data)
    )
    return message.sid

# Example: order confirmation template
send_whatsapp_template(
    to_number='+15559876543',
    template_sid='HXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    template_data={
        '1': 'John Doe',        # customer name
        '2': '#ORD-2026-4719',  # order number
        '3': '$29.99',          # amount
        '4': 'Jun 30, 2026'     # delivery date
    }
)

Receiving WhatsApp Messages

@app.route('/twilio/whatsapp-inbound', methods=['POST'])
def handle_incoming_whatsapp():
    from_number = request.form.get('From', '').replace('whatsapp:', '')
    to_number = request.form.get('To', '').replace('whatsapp:', '')
    body = request.form.get('Body', '').strip()
    num_media = int(request.form.get('NumMedia', 0))

    # Handle media messages
    media_urls = []
    for i in range(num_media):
        media_url = request.form.get(f'MediaUrl{i}')
        media_type = request.form.get(f'MediaContentType{i}')
        media_urls.append({'url': media_url, 'type': media_type})

    # Process the message
    if body.upper() == 'HELP':
        response_text = ("Available options:\n"
                        "1. Track order\n"
                        "2. Talk to support\n"
                        "3. Business hours")
    elif 'TRACK' in body.upper():
        order = database.get_latest_order(from_number)
        response_text = f"Your order #{order['id']} is: {order['status']}"
    else:
        response_text = f"Thanks for reaching out! We'll respond shortly."

    # Create TwiML response
    response = MessagingResponse()
    response.message(response_text)

    return Response(str(response), mimetype='text/xml')

Common Mistakes

1. Not Getting Template Approval

WhatsApp requires pre-approved templates for proactive messages. Submit templates to the WhatsApp Business API for approval before sending.

2. Using Sandbox for Production

The sandbox has limited functionality. Apply for production WhatsApp Business access for real customers.

3. Sending Templates Without Proper Variables

Template variables must be passed as a JSON string via content_variables. Incorrect variable mapping causes message rejection.

4. Forgetting the whatsapp: Prefix

WhatsApp numbers must be prefixed with whatsapp: in both from_ and to parameters.

5. Not Handling Opt-Out

WhatsApp users can block your number. Handle delivery failed callbacks and stop sending to users who block.

Practice Questions

  1. What prefix is used for WhatsApp numbers in Twilio?
  2. What are WhatsApp templates used for?
  3. How do you send a template message?
  4. What is the sandbox number for Twilio WhatsApp?
  5. How do you handle incoming WhatsApp messages?

Answers

  1. whatsapp: prefix. 2. Pre-approved message templates required for proactive messaging. 3. Use content_sid and content_variables parameters. 4. whatsapp:+14155238886. 5. Via an HTTP POST Webhook, similar to SMS.

Challenge

Build a WhatsApp order notification system: customer places an order, system sends an order confirmation template with order details, customer can reply to check status, and a human agent can be escalated for complex queries.

FAQ

What is the Twilio WhatsApp API?

An API for sending and receiving WhatsApp messages through Twilio's platform.

Do I need a WhatsApp Business Account?

Yes, Twilio acts as a Business Solution Provider for WhatsApp.

What are WhatsApp templates?

Pre-approved message formats required for proactive messaging to customers.

Can I send images via WhatsApp API?

Yes, WhatsApp supports images, documents, videos, and audio via the MediaUrl parameter.

What is the WhatsApp sandbox?

A testing environment with limited functionality for development.

Mini Project

Build a WhatsApp customer service bot that: sends order confirmation templates, responds to order status inquiries, escalates to human agents when needed, handles media messages (receiving photos of issues), and integrates with a CRM for ticket creation.

What's Next

  • Learn about Twilio Voice for making and receiving calls
  • Explore Twilio Conversations API for multi-channel chat
  • Continue to Twilio Functions for Serverless logic

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro