RECENT POST

TOP POST

Building a Robust Phone Number Validation Tool With Numverify API and Python

by | Dec 28, 2023

Have you ever faced issues verifying phone numbers in your apps? Wondering how to make sure those digits are correct? Well, you’re in the right place! In this blog, we’ll show you how to build a super-strong phone number verification tool. We will use Numverify phone number validation API and Python.

Why does it matter? Imagine signing up for an app with the wrong phone number – not cool, right? That’s where phone number verification comes in. We’re about to explore how Numverify API can save you with its accurate phone number validation.

Curious about the journey? We’ll break down the app creation process into simple steps. Moreover, we will also guide you through making it work with Python. First, we will cover some basic knowledge. Then, we will move to creating our application. Let’s continue exploring and reading this article until the end. 

Why Do We Need a Phone Number Validation Tool?

We have listed some reasons for needing a phone number validation tool. Let’s explore them one by one: 

✅A phone number tool ensures the information entered is correct. Besides, it helps us avoid mistakes and keep data accurate.

✅It helps people sign up without complications. As a result, the whole process is made easy and hassle-free.

✅By checking phone numbers, we prevent cyber crimes like fake accounts or stealing identities. Therefore, we can make things safer.

✅Valid numbers mean we can chat with users easily through calls or texts. Therefore, we can keep communication smooth.

✅Some places need us to follow the rules. Phone validation helps us do that, especially where being sure of who we’re talking to is super important.

✅It stops us from wasting money on messages or calls that can’t get through. Therefore, we are making sure we only reach real people. It is important to note that the phone validation tool helps us get the right leads faster for our businesses

✅For apps used everywhere, the tool helps handle different phone numbers.

Now that we have learned the reasons for owning a validation tool, let’s explore this further. We have to tell you why choosing Python can be the right decision. 

Why Should You Choose Python for Building a Robust Phone Number Validation Tool?

Here are some reasons to choose Python for building a robust phone number validation tool:

✅Python is simple and easy to pick up, perfect for developers of all levels.

✅Python has a bunch of ready-to-use tools. It’s like having a toolbox full of gadgets for developers.

✅Many developers use Python, so there’s a big group to help when you get stuck. 

✅Python can run on different types of computers without any complications. This means your phone number tool can work smoothly on any computer system.

✅Python lets you build things quickly without sacrificing quality. It’s like having a speedy programming language that doesn’t compromise safety.

✅It is a versatile programming language that helps you build different applications. 

✅Python may not be the fastest, but it’s good enough for most jobs. 

What Factors Do You Consider When Choosing an API for a Phone Number Validation Tool?

We have listed some major factors to consider when choosing an API for a phone number validation tool. Let’s explore those factors one by one to make an informed decision. The following table outlines key considerations:

FactorDescription
AccuracyIt is important to ensure that the API is accurate and precise. Precision in validating phone numbers is essential. The API should minimize false positives and negatives. For example, it should give the right result as to whether a number is valid. 
CoverageThe API should support a wide range of international and local phone number formats and carriers. For example, Numverify covers 232 countries worldwide. 
SpeedRapid response times are crucial for real-time applications. Therefore, you must evaluate the API’s latency and processing speed. The lower the latency, the higher the efficiency of your API. 
DocumentationClear and comprehensive documentation simplifies integration, reducing development time and effort. For example, Numverify gives you interactive API documentation. Once signed up, you can try out the API’s features as you go through their Documentation.
Scalability:The API must handle varying loads gracefully. It can ensure consistent performance as user numbers grow. For example, the API scales accordingly if your business grows with time. 
SecurityRobust security features are also important in the chosen API. Some examples are encryption and authentication, which safeguard sensitive user information. Numverify allows 256-bit HTTPS.
CostConsider the pricing model, including per-request costs, data transfer fees, and hidden charges. You must be able to afford all the charges. Numverify offers the most cost-effective API. Moreover, it can validate 1,000 phone numbers per month for free. Subscriptions start at $14.99 per month.
Compliance:You must ensure the API adheres to relevant data protection and privacy regulations, such as GDPR or CCPA.
Ease of Integration:A well-designed API with SDKs, sample code, and popular programming language support facilitates integration. For example, you can simply identify any national and international phone number by passing it into Numverify’s request URL.
Reliability:Assess the API’s uptime, error-handling mechanisms, and support services. It can help you to ensure continuous functionality.

Let’s explore how you create a validation tool using Numverify.

How Do You Create a Phone Number Validation Tool Using Numverify and Python?

Creating a Phone Number Validation Tool using Numverify and Python involves several key steps. For example, you must set up the environment, understand Numverify API, and handle responses effectively. Let’s explore them one by one. 

Setting up Your Environment

To set up the environment for creating a Phone Number Validation Tool using Numverify and Python, follow these steps:

If you don’t have Python installed, download and install it from the [official Python website](https://www.python.org/). Make sure to check the option to add Python to your system’s PATH during installation.

Python typically comes with pip, the package installer. However, it’s essential to ensure that the pip is up-to-date. Open a command prompt or terminal and run the following command:

python -m pip install --upgrade pip

Create a directory where you will place your project. Then, open the directory. You may run the following commands using the Command Prompt.

mkdir phone_validation_tool
code phone_validation_tool 

Using virtual environments is good practice for isolating your project dependencies. Navigate to your project directory in the command prompt and run:

python -m venv venv

Activate the virtual environment:

On Windows:

venv\Scripts\activate

On macOS/Linux:

source venv/bin/activate

You’ll need the `requests` library to make HTTP requests. Here is the command to install requests:

pip install requests

Your environment is now set up. You can integrate Numverify API into your Python code for phone number validation. Let’s move to the next steps. 

Understanding Numverify API

Before creating a number validation tool, you must understand the chosen API. You must go through the Numverify website. Moreover, you should check the documentation to ensure that it fulfils your project requirements. Analyze the endpoints and test them using platforms like Postman. It will help you get an idea of how this API works. Moreover, you must test an API request before integration into the app.  

First Steps With Numverify in Python

  • Create an account at Numverify. 
  • Navigate to the dashboard and get an API key.
  • Keep your API Key safe. It should not be exposed to users through your website. 
  • Check if it works properly with Python.

Handling API Responses

You must handle API responses in a beautiful way. For example, if the phone number is invalid, it must not show an error. Instead, you should design a beautiful interface for response handling. Don’t worry. We will help you do it by using some expert techniques. Let’s build our sample application now!

Building a Sample Application

In the above steps, we created a directory, activated a virtual environment, and opened the project in Visual Studio Code. Now, it’s time to start working properly on our project. However, before proceeding further, you must know a few things. Our application will be able to perform the following functions:

  1. Single phone number verification.
  2. Map the location of the valid number
  3. Bulk phone number verification. 

Files Required

  1. bulk.html 
  2. index.html 
  3. result.html 
  4. app.py 

Create the above files in your project’s directory. Make sure that you keep all the HTML files in a separate folder and name it “templates”. Let’s explain the code for each file one by one. 

app.py 

1. Importing Libraries:

  from flask import Flask, render_template, request, redirect, url_for
  from flask_socketio import SocketIO
  import requests
  from geopy.geocoders import Nominatim
  import folium
  import pandas as pd

This section imports the necessary libraries for the application.

  • Flask is used for creating a web application.
  • Flask-SocketIO is used for handling WebSocket connections.
  • Requests is used for making HTTP requests.
  • Geopy is used for geocoding (getting location information based on addresses).
  • Folium is used for creating interactive maps.
  • Pandas is used for data manipulation and analysis.

2. Setting Up Flask and SocketIO

  app = Flask(__name__)
  socketio = SocketIO(app)

Creates a Flask web application and a Flask-SocketIO instance.

3. Numverify API Key

 NUMVERIFY_API_KEY = 'ADDYOURAPIKEY'

Sets the API key for the NumVerify service.

4. Phone Number Verification Function

def verify_number(phone_number):
      params = {'access_key': NUMVERIFY_API_KEY, 'number': phone_number, 'format': 1}
      response = requests.get('http://apilayer.net/api/validate', params=params)
      return response.json()

Defines a function (`verify_number`) that sends a request to the Numverify API to validate a given phone number.

5. Flask Routes

Index Route:

python
    @app.route('/')
    def index():
        return render_template('index.html')

Renders the initial HTML page for entering a single phone number.

Validation Route:

@app.route('/validate', methods=['POST'])
    def validate():
        phone_number = request.form.get('phone_number')
        return render_template('result.html', result=result)

Handles the validation form submission, calls `verify_number`, and renders the result on a separate HTML page.

Bulk Validation Route (handles bulk validation from an Excel file):

@app.route('/', methods=['GET', 'POST'])
    def bulk_verify():
        return render_template('bulk.html', results=validation_results)

Handles the bulk validation form submission, reads an Excel file, performs validation for each number. Finally, it renders the result on a separate HTML page.

6. SocketIO Event Handlers

python
  @socketio.on('connect')
  def handle_connect():
      print('Client connected')

  @socketio.on('disconnect')
  def handle_disconnect():
      print('Client disconnected')

Handles WebSocket events when a client connects or disconnects.

7. Run the Application

  if __name__ == '__main__':
      socketio.run(app, debug=True)

Runs the Flask application with SocketIO support in debug mode.

Final Code

The final code looks like below:

from flask import Flask, render_template, request, redirect, url_for

from flask_socketio import SocketIO

import requests

from geopy.geocoders import Nominatim

import folium

import pandas as pd

app = Flask(__name__)

socketio = SocketIO(app)

NUMVERIFY_API_KEY = 'ADD_YOUR_API_KEY'

def verify_number(phone_number):

    params = {'access_key': NUMVERIFY_API_KEY, 'number': phone_number, 'format': 1}

    response = requests.get('http://apilayer.net/api/validate', params=params)

    return response.json()

@app.route('/')

def index():

    return render_template('index.html')

@app.route('/validate', methods=['POST'])

def validate():

    phone_number = request.form.get('phone_number')

    params = {'access_key': NUMVERIFY_API_KEY, 'number': phone_number, 'format': 1}

    response = requests.get('http://apilayer.net/api/validate', params=params)

    result = response.json()

    return render_template('result.html', result=result)

@app.route('/', methods=['GET', 'POST'])

def bulk_verify():

    if request.method == 'POST':

        # Handle file upload

        file = request.files['file']

        # Read Excel file using pandas

        if file and (file.filename.endswith('.xls') or file.filename.endswith('.xlsx')):

            df = pd.read_excel(file, engine='openpyxl')  # Specify the engine for .xlsx files

            # Perform Numverify validation for each number

            validation_results = {}

            for index, row in df.iterrows():

                raw_number = str(row['Phone Number'])

                # Perform Numverify validation directly on the raw phone number

                result = verify_number(raw_number)

                validation_results[raw_number] = result

            return render_template('bulk.html', results=validation_results)

    return render_template('index.html')

@socketio.on('connect')

def handle_connect():

    print('Client connected')

@socketio.on('disconnect')

def handle_disconnect():

    print('Client disconnected')

if __name__ == '__main__':

    socketio.run(app, debug=True)

Before moving towards the HTML files, make sure you created a separate folder “templates”. All your HTML files should be placed in that folder. 

bulk.html 

1. Setting the HTML Basic Structure for Our App:

<!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Verification Results</title>

2. Style Section:

<style>
      /* Add your preferred styling colors and elements in this section */
  </style>

3. Body Section:

<body>
    <h1>Verification Results</h1>
    <table>
        <tr>
            <th>Phone Number</th>
            <th>Validation Result</th>
            <th>Local Format</th>
            <th>Intl. Format</th>
            <th>Country</th>
            <th>Location</th>
            <th>Carrier</th>
            <th>Line Type</th>
        </tr>
        {% for number, result in results.items() %}
            <tr>
                <td>{{ number }}</td>
                <td>{{ "✔️Valid" if result and result.valid else "❌Invalid" }}</td>
                <td>{{ result.local_format if result and result.valid else "N/A" }}</td>
                <td>{{ result.international_format if result and result.valid else "N/A" }}</td>
                <td>{{ result.country_name if result and result.valid else "N/A" }}</td>
                <td>{{ result.location if result and result.valid else "N/A" }}</td>
                <td>{{ result.carrier if result and result.valid else "N/A" }}</td>
                <td>{{ result.line_type if result and result.valid else "N/A" }}</td>

            </tr>
        {% endfor %}
    </table>
</body>

The body section performs the following functions:

  • Displays a heading “Verification Results”.
  • Defines a table to display verification results.
  • Defines the header row of the table with column headers like “Phone Number,” “Validation Result,” etc.
  • Uses Jinja2 templating to loop through items in the `results` dictionary and generate table rows with phone number details.
  • Populates the table cells with dynamic content using Jinja2 syntax, displaying phone number details such as:
  • Validation result
  • Local format
  • International format
  • Country
  • Location
  • Carrier
  • Line type.
Final Code

The final code to enable bulk verification looks like below:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Verification Results</title>

    <style>

        body {

            font-family: 'Arial', sans-serif;

            background-color: #fce4ec; /* Light pink background color */

            color: #333; /* Dark text color */

            margin: 0;

            padding: 0;

        }

        h1 {

            background-color: #e91e63; /* Pink background color for the heading */

            color: #fff; /* White text color */

            padding: 20px;

            text-align: center;

        }

        table {

            width: 100%;

            border-collapse: collapse;

            margin-top: 20px;

        }

        th, td {

            padding: 15px;

            text-align: left;

            border: 1px solid #ccc; /* Light gray border */

        }

        th {

            background-color: #ff80ab; /* Lighter pink background color for header cells */

            color: #fff; /* White text color */

        }

        tr:nth-child(even) {

            background-color: #f8bbd0; /* Alternate row color for better readability */

        }

    </style>

</head>

<body>

    <h1>Verification Results</h1>

    <table>

        <tr>

            <th>Phone Number</th>

            <th>Validation Result</th>

            <th>Local Format</th>

            <th>Intl. Format</th>

            <th>Country</th>

            <th>Location</th>

            <th>Carrier</th>

            <th>Line Type</th>

        </tr>

        {% for number, result in results.items() %}

            <tr>

                <td>{{ number }}</td>

                <td>{{ "✔️Valid" if result and result.valid else "❌Invalid" }}</td>

                <td>{{ result.local_format if result and result.valid else "N/A" }}</td>

                <td>{{ result.international_format if result and result.valid else "N/A" }}</td>

                <td>{{ result.country_name if result and result.valid else "N/A" }}</td>

                <td>{{ result.location if result and result.valid else "N/A" }}</td>

                <td>{{ result.carrier if result and result.valid else "N/A" }}</td>

                <td>{{ result.line_type if result and result.valid else "N/A" }}</td>

            </tr>

        {% endfor %}

    </table>

</body>

</html>

index.html 

1. Setting the Basic HTML Structure & Styles

<!DOCTYPE html>
  <html lang="en">
  <head>       <style>
      /* Add your preferred styling colors and elements in this section */
      </style>
    </head>

2. Page Content

<body>
    <h1>Single Number Verification</h1>
    <form action="/validate" method="post">
        <label for="phone_number">Enter Phone Number:</label>
        <input type="text" name="phone_number" required>
        <button type="submit">Validate</button>
    </form>
    <h1>Bulk Number Verification</h1>
    <form action="/" method="post" enctype="multipart/form-data">
        <label for="file">Upload Excel File:</label>
        <input type="file" name="file" accept=".xls, .xlsx">
        <button type="submit">Verify Numbers</button>
    </form>

The body section performs the following functions:

Section 1:

  • Displays a heading for single number verification.
  • Contains a form for submitting a single phone number for validation.
  • Input field for entering a phone number.
  • Validate button to submit the form.

Section 2:

  • Displays a heading for bulk number verification.
  • Contains a form for uploading an Excel file for bulk number validation.
  • Input field for selecting a file (limited to .xls and .xlsx extensions). You may enter other file types by inserting the formats in this part of code.
  • Verify Numbers button to submit the form.
Final Code

The final code for index.html looks like below:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Phone Number Validation</title>

    <style>

        html, body {

            font-family: 'Times New Roman';

            margin: 0;

            padding: 0;

            height: 100%;

        }

        body {

            background: url('https://files.123freevectors.com/wp-content/original/119522-abstract-pastel-pink-background-image.jpg');

            background-size: cover;

            background-position: center;

            color: #fff;

        }

        h1 {

            text-align: center;

            padding: 20px;

            color: black;

            font-weight: bold;

        }

        form {

            margin: 20px auto;

            max-width: 400px;

            background: rgba(255, 224, 230, 0.8); /* Light pink background */

            padding: 20px;

            border-radius: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);

        }

        label {

            display: block;

            margin-bottom: 10px;

            color: black; /* Dark text color for label */

            font-weight: bold;

        }

        input {

            width: calc(100% - 20px);

            padding: 10px;

            margin-bottom: 15px;

            box-sizing: border-box;

            border: 1px solid #ccc;

            border-radius: 5px;

        }

        button {

            background-color: #e91e63; /* Pink background color for button */

            color: #fff;

            padding: 12px;

            border: none;

            cursor: pointer;

            width: 100%;

            border-radius: 5px;

        }

        button:hover {

            background-color: #c2185b; /* Darker pink on hover */

        }

        a {

            color: #fff;

            text-decoration: none;

        }

        a:hover {

            text-decoration: underline;

        }

    </style>

</head>

<body>

    <h1>Single Number Verification</h1>

    <form action="/validate" method="post">

        <label for="phone_number">Enter Phone Number:</label>

        <input type="text" name="phone_number" required>

        <button type="submit">Validate</button>

    </form>

    <h1>Bulk Number Verification</h1>

    <form action="/" method="post" enctype="multipart/form-data">

        <label for="file">Upload Excel File:</label>

        <input type="file" name="file" accept=".xls, .xlsx">

        <button type="submit">Verify Numbers</button>

    </form>

</body>

</html>

Result.html

1. Basic HTML Structure:

 <!DOCTYPE html>
  <html lang="en">
  <head>
      <style>
        </style>
  </head>

2. Body Section:

<body>
    <div id="container">
        <h1>Validation Result</h1>
        {% if result.valid %}
            <!-- Valid phone number section -->
            <p>The phone number is valid! 🤗✅</p>
            <p><strong>Local Format:</strong> {{ result.local_format }}</p>
            <p><strong>International Format:</strong> {{ result.international_format }}</p>
            <p><strong>Country:</strong> {{ result.country_name }} ({{ result.country_code }})</p>
            <p><strong>Location:</strong> {{ result.location }}</p>
            <p><strong>Carrier:</strong> {{ result.carrier }}</p>
            <p><strong>Line Type:</strong> {{ result.line_type }}</p>
            <!-- Map Country link example (replace with actual map service link) -->
            <a class="button" href="https://www.google.com/maps/search/{{ result.country_name }}">Locate Country 🌎</a>
        {% else %}
            <!-- Invalid phone number section -->
            {% if result.error %}
                <p id="error-message">Invalid phone number. Reason: {{ result.error.info }}</p>
            {% else %}
                <p id="error-message">Invalid phone number 😞</p>
            {% endif %}
        {% endif %}
        <br>
        <a class="button" href="/">Back to Home 🔙</a>
    </div>
</body>

The body part of this HTML file performs the following functions:

  • Displays a container with the title “Validation Result.”
  • Uses template logic to conditionally render content based on whether the phone number is valid or not.
  • If the phone number is valid, it displays details such as local format, international format, country, location, carrier, line type, and a button to locate the country on a map.
  • If the phone number is invalid, it shows an error message.
  • Provides a “Back to Home” button with a link to the home page.

Final Code

The final code is given as under: 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Validation Result</title>

    <style>

        html, body {

            font-family: 'Times New Roman';

            margin: 0;

            padding: 0;

            height: 100%;

        }

        body {

            background: url('https://files.123freevectors.com/wp-content/original/119522-abstract-pastel-pink-background-image.jpg');

            background-size: cover;

            background-position: center;

            color: #fff;

            display: flex;

            align-items: center;

            justify-content: center;

        }

        #container {

            background: rgba(255, 224, 230, 0.8); /* Light pink background */

            padding: 20px;

            border-radius: 10px;

            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);

            text-align: center;

        }

        h1 {

            color: #333; /* Dark text color */

            font-weight: bold;

        }

        p {

            color: #333; /* Dark text color */

        }

        strong {

            color: #333; /* Dark text color */

        }

        #error-message {

            color: red; /* Pink color for error messages */

            font-weight: bold;

            margin-top: 15px;

            font-size: 22px;

        }

        a.button {

            display: inline-block;

            background-color: #e91e63; /* Pink background color for the button */

            color: #fff;

            padding: 10px 20px;

            text-decoration: none;

            border-radius: 5px;

            margin-top: 15px;

            transition: background-color 0.3s ease;

        }

        a.button:hover {

            background-color: #c2185b; /* Darker pink on hover */

        }

        a {

            color: #fff;

            text-decoration: none;

        }

        a:hover {

            text-decoration: underline;

        }

    </style>

</head>

<body>

    <div id="container">

        <h1>Validation Result</h1>

        {% if result.valid %}

            <!-- Valid phone number section -->

            <p>The phone number is valid! 🤗✅</p>

            <p><strong>Local Format:</strong> {{ result.local_format }}</p>

            <p><strong>International Format:</strong> {{ result.international_format }}</p>

            <p><strong>Country:</strong> {{ result.country_name }} ({{ result.country_code }})</p>

            <p><strong>Location:</strong> {{ result.location }}</p>

            <p><strong>Carrier:</strong> {{ result.carrier }}</p>

            <p><strong>Line Type:</strong> {{ result.line_type }}</p>

            <!-- Map Country link example (replace with actual map service link) -->

            <a class="button" href="https://www.google.com/maps/search/{{ result.country_name }}">Locate Country 🌎</a>

        {% else %}

            <!-- Invalid phone number section -->

            {% if result.error %}

                <p id="error-message">Invalid phone number. Reason: {{ result.error.info }}</p>

            {% else %}

                <p id="error-message">Invalid phone number 😞</p>

            {% endif %}

        {% endif %}

        <br>

        <a class="button" href="/">Back to Home 🔙</a>

    </div>

</body>

</html>

Output

Let’s run our application now. Run the command “python app.py” It will display a page as under: 

Output Screen of the Phone Number Validation tool

Single Number Verification:

If the number is valid, we get the following response. Moreover, you may click on “Locate Country” to get the detailed location information for the valid number.

Output Screen of the Phone Number Validation tool: Single Number Verification
Output Screen of the Phone Number Validation tool: locate the country on the map

If the phone number is invalid, we get the results as under:

Output Screen of the Phone Number Validation tool: phone number is invalid

Let’s try bulk number verification. You should have an Excel file listed with phone numbers. Upload it to the bulk phone number verification section. The results will be shown as under:

bulk number verification output screen

Conclusion

In the above article, we used Numverify and Python to create a phone validation tool. We also guided users to choose the right API for their project. Then, we showed how to set up an environment and create an application. Users can try this app on their system and verify a single and large data set of numbers. 

FAQs

Why Should You Choose Numverify?

It is easy to integrate with multiple programming languages, including Python. 

What Is the Best API to Create a Phone Validation Tool?

Numverify is one of the best APIs to create a phone validation tool.

What Are the Reasons to Choose Python With Numverify?

Python is a versatile language that makes it easy to create apps using APIs. 

What Are the Applications of a Bulk Phone Validation Tool?

You can use it to verify the numbers of your patients, customers, and website users.

Sign Up for free at Numverify – Create a reliable phone validation tool Today!