This tutorial builds a click-to-call feature using Flask and Twilio in Python that takes a visitor's phone number from a web form, dials them via Twilio, and then connects them to a support or sales agent. It targets developers who want to reduce friction by letting website visitors get a real call instead of waiting on hold or filling out a contact form. You will build a Flask endpoint that accepts the visitor's number, initiates a Twilio call bridging the visitor to an agent, and returns a confirmation response to the browser.
Prerequisites and Setup
You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask python-dotenv. Your application needs a Twilio number to call out from, and a TwiML endpoint that dials the agent's number once the visitor answers. Store the agent's number in an environment variable so it can be changed without modifying code. The flow is: form submission triggers Flask POST handler, Flask calls Twilio API to dial the visitor, visitor answers, Twilio fetches TwiML that dials the agent, both parties are connected.
pip install twilio flask python-dotenv
# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
AGENT_PHONE_NUMBER=+15559998888
The Complete Code
The Flask form endpoint receives the visitor's phone number, validates it is in E.164 format, and calls client.calls.create() to dial the visitor. The url parameter points to a TwiML route on the same Flask app that tells Twilio to dial the agent's number once the visitor picks up. This creates a bridge where Twilio dials the visitor, they answer, and then Twilio immediately dials the agent and connects both parties. The visitor hears a brief greeting before being connected, giving the agent a few seconds to prepare for the incoming call.
import os
from flask import Flask, request, jsonify, render_template_string
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse, Dial
from twilio.base.exceptions import TwilioRestException
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])
FROM = os.environ["TWILIO_PHONE_NUMBER"]
AGENT = os.environ["AGENT_PHONE_NUMBER"]
FORM = """
<html><body>
<h2>Get a callback from our team</h2>
<form method="POST" action="/call">
<input name="phone" placeholder="+15551234567" required />
<button type="submit">Call Me Now</button>
</form>
</body></html>
"""
@app.route("/")
def index():
return FORM
@app.route("/call", methods=["POST"])
def click_to_call():
visitor_phone = request.form.get("phone", "").strip()
if not visitor_phone.startswith("+"):
return jsonify({"error": "Phone must be in E.164 format, e.g. +15551234567"}), 400
try:
call = client.calls.create(
to=visitor_phone,
from_=FROM,
url=request.url_root.rstrip("/") + "/connect-agent",
)
return jsonify({"message": "Calling you now!", "sid": call.sid}), 200
except TwilioRestException as e:
return jsonify({"error": e.msg}), 500
@app.route("/connect-agent", methods=["POST"])
def connect_agent():
resp = VoiceResponse()
resp.say("Please hold for a moment while we connect you to a specialist.", voice="alice")
dial = Dial(callerId=FROM)
dial.number(AGENT)
resp.append(dial)
return str(resp), 200, {"Content-Type": "text/xml"}
if __name__ == "__main__":
app.run(port=5000, debug=True)
Testing and Debugging
Submit the form with your own mobile number and wait for Twilio to call you within a few seconds. When you answer, you should hear the greeting and then be connected to the agent number you configured. If the visitor's phone rings but no one is called on the agent side, check that your ngrok URL is correct in the url parameter and that the /connect-agent route is returning valid TwiML. Error code 13224 in the Twilio Console means Twilio could not fetch the TwiML from your /connect-agent endpoint; verify your server is running and the route is accessible.
Taking It Further
Add agent availability logic that checks a schedule or an on-call system before initiating the call, and plays a voicemail TwiML if no agents are available instead of connecting. Implement call queuing using Twilio TaskRouter or Queues so multiple click-to-call requests are handled in order when agents are busy. Log each click-to-call event to a database with the visitor's number, timestamp, call SID, and outcome for conversion tracking. Add a caller ID whisper by wrapping the Dial in a Conference so the agent hears a brief whisper about the source page before the visitor is connected.
Contact Telphi Consulting to implement a full click-to-call solution with agent routing, analytics, and CRM integration.
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.