Hello their fellow nerds, Arsey here and welcome to this tutorial! In this guide, we’ll walk through how to build a simple voice-based balance inquiry system using flask and AfricasTalking Voice API. The idea is simple: when a user calls our service, the will hear a voice response informing them of the account balance.
Let’s get started!
We’re creating a Flask web service that integrates with AfricasTalking Voice API to:
- Receive incoming calls.
- Check the caller’s balance in a simulated database.
- Read out the balance using text-to-speech.
- End the cal gracefully.
This is a great way to build IVR (Interactive Voice Response) systems for services like banking, customer support and more!
Setting Up Our AfricasTalking Account, Phone Number, and Callback URL
Before we can test our voice-based inquiry system, we need to set up our AfricasTalking account, register phonenumber, and configure our callback URL. Sounds like hard work, no… just follow these steps to get everything ready!
Create an AfricasTalking Account
If you don’t have an account yet, sign up for free on AfricasTalking or else login into their platform.
Steps to create an account:
- Go to AfricasTalking Sign-up Page.
- Click Sign Up and enter your details.
- Verify your email and log in to your account
- Now due to security purposes they might send a Two-Factor Authentication so make sure you check your email for the OTP sent.
- Now you’ll be logged in into your account
Getting a phone Number for Voice calls
AfricasTalking provides sandbox numbers for testing in their developer environment. But for the sandbox environment it’s not supported yet so we we’ll use a live environment, and that's good approach to test in a live enviroment.
Steps to get a test phone number:
-
Log in to your AfricasTalking Dashboard
-
Click on the prominent green plus icon to create a new team and enter the team name and save
-
A new team will be created, click on it and look for the create app button, enter the your app name, your username ( let’s say you appname is InquireBal, the username could be the same but with lowercase letters like inquirebal), then choose a country and currency code, and save.
-
Now you’ll have your app ready, now navigate to the side panel and choose voice, under voice click on phone Numbers, if you don’t have a phone Number, create one by navigating to the side panel, click on request this will display a form so enter the fields.

- In the category section, choose regular: business Number - Enter your name/organization and email. - choose a country and a telecom provider - You can add additional comments but it’s optional then hit the submit request button
Wait for some few minutes and you’ll have your phone number ready to verify go back to phone numbers under the voice product if you see number, congrats, you have done the first part. Sip on some coffee, have some snacks because we’re now going to build our Voice based inquiry system. Done, let’s now build our product.
Before we dive into code, ensure you hve Python and flask installed. If not, install python form their official website and then install flask using this command in your terminal or command prompt on you PC
pip install flask
Now let’s build th flask App
from flask import Flask, request, Response # Import necessary modules from Flask and for XML handling
import xml.etree.ElementTree as ET # Import ElementTree for XML parsing (not used in this example)
app = Flask(__name__) # Create an instance of the Flask class, which represents the web application
@app.route('/checkBalance') # Define a route for the URL path '/checkBalance'
def check_balance():
return "Check MyBalance" # Return a simple string response when this route is accessed
if __name__ == '__main__': # Ensure the script runs only when executed directly (not imported as a module)
app.run(debug=True) # Start the Flask development server with debugging enabledThis code sets up a basic Flask web server. It defines a single route (/checkBalance) that responds with the text "Check MyBalance" when accessed. Flask is a lightweight web framework that allows you to define routes and handle HTTP requests easily. The debug=True option enables debugging features, such as auto-reloading the server on code changes and providing detailed error messages.
from flask import Flask, request, Response
import xml.etree.ElementTree as ET
app = Flask(__name__)
BALANCE_DB = {
# use your phone number instead
'+256707522509': 2000,
}
@app.route('/checkBalance', methods=['POST'])
def check_balance():
session_id = request.form.get('sessionId')
is_active = request.form.get('isActive')
if is_active == '1':
caller_number = request.form.get('callerNumber')
if caller_number in BALANCE_DB:
balance = BALANCE_DB[caller_number]
text = f"Arsey, you balance is {balance} shillings. Good bye."
else:
text = "Sorry, your phone number is not registered for this service. Good Bye."
# Creae XML Response
response = ET.Element('Response')
say_element = ET.SubElement(response, 'Say')
say_element.text = text
# Convert XML to String
xml_response = ET.tostring(response, encoding='utf-8', method='xml')
return Response(xml_response, mimetype='text/xml')
else:
duration = request.form.get('durationSeconds')
currency_code = request.form.get('currencyCode')
amount = request.form.get('amount')
# In a real world application, you would store these details in a database.
# For Example:
# log_call_details(duration, currency_code, amount)
return '', 204 # No Content response
if __name__ == '__main__':
app.run(debug=True)How does this code work
Let's break dow the key parts of the code.
Handling incoming calls
When a call comes in, AfricasTalking sends a post request to our /checkBalance endpoint with details like:
- sessionId --> a unique ID for the call.
- isAcive --> indicates if the call is still ongoing (1) or has ended (0).
- callerNumber --> the phone number of the caller.
Here we first check if the call is active:
is_actve = request.form.get('isActive')
if is_active == '1':Retrieving the caller's balance
We then get the caller's phone number and check of it exists in our BALANCE_DB:
caller_number = request.form.get('callerNumber')
if caller_number in BALANCE_DB:
balance = BALANCE_DB[caller_number]
text = f"Arsey, you balance is {balance} shillings. Good bye."
else:
text = "Sorry, your phone number is not registered for this service. Good Bye."And if the caller is found, we read out their balance. otherwise, we let them know they are not registered.
Responding with a voice
AfricasTalking expects an XML response for voice interactions. we create one like this:
response = ET.Element('Response')
say_element = ET.SubElement(response, 'Say')
say_element.text = textthen, we convert it to XML and return it.
xml_response = ET.tostring(response, encoding='utf-8', method='xml')
return Response(xml_response, mimetype='text/xml')Handling Call Completion.
When a call ends, we get additional details like call duration, currency_code, amout charged. we can log thes details if needed.
else:
duration = request.form.get('durationSeconds')
currency_code = request.form.get('currencyCode')
amount = request.form.get('amount')To test this locally, run:
python main.py
However, AfricasTalking cannot acess your localhost, so you need to have live url or expose it using ngrok, there are many tools for the job but i recommend using replit or pythonanywhere for simplicity in this guide we'll use replit.
Create a Replit Account
If you don't have one already,, signup for free at Replit.
To deploy your Flask app, we’ll use Replit for simplicity. Follow these steps:
If you don’t already have an account, sign up for free at Replit.
This will load your development environment.
- Open the
main.pyfile in your Replit project. - Delete the existing code in
main.py. - Paste your voice-based Flask code into the file.

- Click the green Run button to start the server.

- In the webview preview, click the URL provided by Replit.

- Copy the URL for the next step.

- Go to your AfricasTalking dashboard.

- Under Phone Numbers, click the three horizontal dots next to your number.

- Select Callback and paste your Replit URL, appending
/checkBalanceto it.

Make sure to append /checkBalance after the url you pasted

- Save the changes.
- Dial the phone number provided by AfricasTalking.
- You should hear the account balance or a message indicating the phone number is not registered.
Congratulations! Your voice-based balance inquiry system is now live.
.jpeg)

