This tutorial shows how to initiate an outbound phone call from Python using the Twilio REST API, with a TwiML URL that controls what happens when the call connects. It targets developers adding automated voice alerts, appointment reminders, or call flows to their applications. You will trigger a real call that reads a message aloud using Twilio's text-to-speech engine and then hangs up.
Prerequisites and Setup
You need Python 3.7 or higher, the Twilio SDK installed, and a Twilio voice-enabled number. Install dependencies with pip install twilio flask python-dotenv and configure your credentials in a .env file. The url parameter in calls.create() must point to a publicly reachable HTTPS endpoint that returns TwiML XML; you can host this as a Flask route exposed via ngrok during development. Make sure the TwiML endpoint does not require authentication, because Twilio fetches it as an anonymous HTTP client when the call connects.
pip install twilio flask python-dotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
The Complete Code
The client.calls.create() method takes a url argument pointing to your TwiML, a to number, and a from_ number. Twilio dials the to number and, once the call is answered, fetches the TwiML at your url to determine what to say or play. The Flask route returns a <Say> verb that uses Twilio's Alice voice to speak the message text. The returned CallInstance object contains a sid you can use to monitor or cancel the call.
import os
from flask import Flask
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
@app.route("/voice", methods=["GET", "POST"])
def voice():
resp = VoiceResponse()
resp.say("Hello. This is an automated message from Telphi Consulting.", voice="alice")
return str(resp), 200, {"Content-Type": "text/xml"}
def make_call(to_number: str, twiml_url: str):
call = client.calls.create(
to=to_number,
from_=os.environ["TWILIO_PHONE_NUMBER"],
url=twiml_url,
)
print(f"Call SID: {call.sid} Status: {call.status}")
return call.sid
if __name__ == "__main__":
# Run Flask in a separate process and expose via ngrok,
# then pass the ngrok URL here.
make_call("+15551234567", "https://xxxx.ngrok.io/voice")
Testing and Debugging
Start your Flask server and ngrok tunnel, copy the ngrok HTTPS URL, and pass it as the url to make_call(). If the call SID prints but the phone never rings, check that the to number is verified under Verified Caller IDs on trial accounts. Error code 13224 means Twilio could not fetch your TwiML URL; verify the URL is publicly reachable by pasting it into a browser. Check the Twilio Console under Monitor for the exact HTTP status code Twilio received when it fetched your TwiML endpoint.
Taking It Further
Add a status_callback URL to calls.create() so Twilio POSTs call lifecycle events (initiated, ringing, answered, completed) to your server for logging. Pass machine_detection="Enable" to activate answering machine detection so your TwiML can respond differently to humans versus voicemail systems. Use the timeout parameter to control how many seconds Twilio lets the call ring before considering it unanswered. For dynamic messages, embed query parameters in the TwiML URL or use a Twilio Function that reads call data from a database before constructing the TwiML response.
Get in touch with Telphi Consulting to design automated outbound call campaigns with advanced call tracking and analytics.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.