How to integrate WhatsApp with Twilio: The practical guide

September 22, 2025 • 6 min read

Home / Blog / How to integrate WhatsApp with Twilio: The practical guide
How to integrate WhatsApp with Twilio: The practical guide | Learn how to integrate WhatsApp with Twilio in a practical, step-by-step guide

Introduction

Hey there! If you're looking to add WhatsApp messaging to your app or business workflow, without worrying about the WhatsApp Business API, Twilio makes it surprisingly straightforward. WhatsApp is huge for customer communication, especially in regions where it's the go-to messaging app. By integrating it with Twilio, you can send notifications, handle support chats, or even automate reminders, all programmatically.

 

In this guide, I'll walk you through the process step by step, starting with Twilio's sandbox for testing (no real costs or approvals needed upfront) and then moving to production using WhatsApp senders. WhatsApp senders are essentially your approved phone numbers tied to a WhatsApp Business Account, which let you send messages at scale under your brand.

 

We'll use Python for the code examples because it's beginner-friendly, but Twilio supports tons of languages like PHP, Node.js, Java, and more. Let's dive in!

 

Prerequisites

Before we start, you'll need:

 

  • A free Twilio account (sign up at twilio.com if you don't have one).
  • Python installed on your machine (version 3.6+ works fine).
  • The Twilio Python library: Install it with pip install twilio.
  • A WhatsApp-enabled phone number (your personal one for testing).
  • For production, a Facebook Business Manager account and a dedicated phone number for your WhatsApp Business Account.
  • Basic comfort with environment variables and running scripts from the terminal.

 

Twilio handles the heavy lifting with their API, so you don't need to deal directly with WhatsApp's backend.

 

Step 1: Sign Up for Twilio and Get Your Credentials

  1. Head over to twilio.com/try-twilio and create a free account. You'll get $15 in trial credits to play around with.
  2. Once logged in, go to the Twilio Console dashboard. Here, you'll find your Account SID and Auth Token, these are like your API keys. Copy them somewhere safe.
  3. Set them as environment variables to keep things secure (don't hardcode them in your scripts!). On macOS/Linux, open your terminal and run:

     

    export TWILIO_ACCOUNT_SID='your_account_sid_here'
    export TWILIO_AUTH_TOKEN='your_auth_token_here'

    On Windows, use set instead of export.

 

This setup ensures your code can authenticate with Twilio's servers.

 

Step 2: Set Up the Twilio Sandbox for WhatsApp

The sandbox is a testing environment where you can send and receive messages without full WhatsApp approval. It's perfect for prototyping.

  1. In the Twilio Console, navigate to Messaging > Try it out > Send a WhatsApp message. Or go to console.twilio.com/us1/develop/sms/try-it-out/whatsapp-learn.
  2. Acknowledge the terms and click Confirm to activate the sandbox. You'll see a sandbox phone number (something like +14155238886) and a unique code phrase (like "join apple-tree").
  3. On your phone, open WhatsApp and send the message join <your-sandbox-code> (e.g., "join apple-tree") to the sandbox number. WhatsApp will reply confirming you're connected.
  4. If you want to disconnect later, just reply "stop" to the sandbox number.

 

Pro tip: Only numbers that have joined the sandbox can interact with it. For testing with multiple users, have them join too. This is all free during the trial.

 

Step 3: Send Your First WhatsApp Message

Now, let's send a message from your code to your phone via the sandbox.

  1. Create a new Python file called send_whatsapp.py.
  2. Paste in this code:

     

    from twilio.rest import Client
    import os
    
    # Grab your credentials from environment variables
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['TWILIO_AUTH_TOKEN']
    client = Client(account_sid, auth_token)
    
    message = client.messages.create(
        from_='whatsapp:+14155238886',  # Your sandbox number
        body='Hello from Twilio! This is your first WhatsApp message.',
        to='whatsapp:+12345678901'  # Your WhatsApp number in E.164 format (e.g., +1 for US)
    )
    
    print(f"Message SID: {message.sid}")
  3. Replace the to value with your own WhatsApp number (include the country code, like +15551234567).
  4. Replace the from_ with your actual sandbox number.
  5. Save the file and run it: python send_whatsapp.py.
  6. Check your WhatsApp, you should see the message pop up!

 

If it works, congrats! You've just sent a programmatic WhatsApp message. Note: For business-initiated messages outside a 24-hour reply window, you'll need pre-approved templates in production.

 

Step 4: Receive Messages and Set Up an Automated Reply

To make it two-way, you need a webhook to handle incoming messages.

  1. Install Flask (a lightweight web framework): pip install flask.
  2. Create a new file called reply_whatsapp.py:

     

    from flask import Flask, request
    from twilio.twiml.messaging_response import MessagingResponse
    
    app = Flask(__name__)
    
    @app.route('/whatsapp', methods=['POST'])
    def whatsapp_reply():
        # Get the incoming message
        incoming_msg = request.values.get('Body', '').lower()
        resp = MessagingResponse()
        msg = resp.message()
    
        # Simple echo reply for testing
        msg.body(f'You said: {incoming_msg}. Thanks for chatting!')
    
        return str(resp)
    
    if __name__ == '__main__':
        app.run(port=3000)
  3. Run the server: python reply_whatsapp.py.
  4. To expose your local server to the internet (Twilio needs a public URL), use ngrok: Download it from ngrok.com, then run ngrok http 3000. Note the forwarding URL (e.g., https://abc123.ngrok.io).
  5. Back in the Twilio Console, go to the WhatsApp sandbox settings. In the "When a message comes in" field, paste your ngrok URL with /whatsapp appended (e.g., https://abc123.ngrok.io/whatsapp). Set the method to POST and save.
  6. Test it: Send a message from your WhatsApp to the sandbox number. You should get an automated reply echoing your message.

 

This webhook setup is crucial for real apps since you can expand it to integrate with databases, AI, or other services.

 

Step 5: Go to Production with WhatsApp Senders

Once testing is done, switch to production for real users.

  1. Set up a WhatsApp Business Account (WABA) via Facebook Business Manager if you don't have one.
  2. In the Twilio Console, go to Messaging > Senders > WhatsApp Senders.
  3. Click Get Started and follow the self-sign-up process: Link your WABA, verify your phone number, and get approval from WhatsApp (this can take a few days).
  4. Once approved, your sender (phone number) will appear in the console. Update your code's from_ to use this: whatsapp:+your-approved-number.
  5. For templates, submit them via the Twilio Console for WhatsApp approval as it is required for proactive messages.

Pricing: Messages cost about $0.005–$0.01 each, depending on the region. Monitor your usage in the console.

 

Common Pitfalls and Tips

  • Rate Limits: Sandbox has limits (e.g., 1 message/second). Production scales better.
  • Templates: Always use approved templates for outbound messages to avoid blocks.
  • Debugging: Check Twilio's debugger in the console for errors.
  • Security: Never expose your Auth Token publicly.
  • Scaling: For advanced stuff, look into Twilio's Conversations API for multi-channel support.

 

Conclusion

And there you have it, a fully functional WhatsApp integration! This guide covers the most crutial pieces in order to get started with WhatsApp messaging, and Twilio makes it easy to use without having to worry too much about setting custom APIs for the WhatsApp Business setup. As you can see, you can send messages programatically in a few lines of code.

165
Twilio,  Python
Published on September 22, 2025

Ready to take your project to the next level?

Contact me

About the author

Author

Gonzalo Gomez

Sr. Software Engineer

Senior software engineer located in Buenos Aires, Argentina. I specialize in building highly scalable web applications and I've been delivering MVPs and helping companies with their digital transformation for the past 7 years. I am proficient in a variety of technologies, including Laravel, Vue.js, Twilio, AWS, React.js, Node.js and MySQL.

Subscribe to my newsletter

If you enjoy the content that I make, you can subscribe and receive insightful information through email. No spam is going to be sent, just updates about interesting posts or specialized content that I talk about.

Related posts

Why a programming bootcamp is no longer enough

April 11, 2024
Let's be honest, most of the people that start in the IT industry go the programming path because it's one of the main branches that... Continue reading

Stop Overbuilding: Start With Twilio Flex and Grow When You Need To

April 22, 2025
Introduction In the rush to deliver seamless customer service, too many companies fall into the trap of overbuilding their contact center infrastructure. They invest heavily upfront—custom... Continue reading

How to handle multiple projects with Python using virtual environments

August 20, 2025
IntroductionPython is one of the most popular programming languages nowadays. It typically is the go-to option when doing Data Science, Machine Learning, and AI development.... Continue reading