📌 Purchasing Numbers in Bulk - Python, Node.js, & cURL

Enjoy this user-friendly approach to adding API search parameters through queries in your console. Whether you want to buy local or purchase toll-free, this guide can help find all the numbers that suit your needs and seamlessly add them to your project.

Overview

This is a code snippet that runs two Number APIs, one to search for available numbers and the second is to purchase the available list of numbers. The console will print out questions that specify what parameters are intended by the user.

To quickly run this code, check out our recipe below and replace the variables with your own!

❗️

Number Release Policy

Numbers that have been purchased in your account, will not be able to be released for 14 days.

Be sure to only purchase the numbers that are needed. You can always come back for more!

What are we going to do?

The goal is to order as many numbers that are needed, in the most simplistic way possible. These numbers can be customized to the user's preferences via parameters in our API requests.

These queries are then entered into our SignalWire Compatible APIs to search for available local numbers and search for available Toll-Free numbers. Once the correct amount and type of numbers are found, we will then use the create an incoming phone number API to purchase and place these numbers into a space.

📘

API Limitations

With great power, comes great responsibility.

As a preemptive measure to prevent any unwanted purchases, this API will limit the user to only pulling 100 numbers at a time. This means that you will need to execute this code multiple times if you wish to purchase more than 100 at a given time.

cURL

Below is a working bash script example using the SignalWire REST API to purchase numbers in bulk. It generally takes two actions to purchase a single phone number.

  • Get a list of available phone numbers function
sw_bulk_number_available () {
  • Purchase a number from the list function
sw_bulk_number_available () {

Code Walkthrough

Let's explain some key parts of each function.

In the available function, for optimal randomization purposes, we get a list from a Region instead of an area code, for local numbers. We're making a curl request to SignalWire with the InRegion attribute, which will give back a JSON response of 50 numbers. Then, we use a linux utility "jq" to parse the JSON response, giving us only the numbers themselves.

declare -a REGION=(AL AK AZ AR CA CO CT DE FL GA

               HI ID IL IN IA KS KY LA ME MD
               MA MI MN MS MO MT NE NV    NJ
               NM NY NC ND OH OK OR PA RI SC
               SD TN TX UT VA    WA WV WI WY)
    RAND=$(( RANDOM % (47 - 0 + 1 ) + 0 ))
    RANDOM_REGION=${REGION[${RAND:-1}]}
    PHONE_LIST=$(curl --silent https://$SW_SPACE_URL/api/laml/2010-04-01/Accounts/$SW_PROJ_KEY/AvailablePhoneNumbers/US/Local.json \
         -X GET \
         -d "InRegion=$RANDOM_REGION" \
         -u "$SW_PROJ_KEY:$SW_TOKEN" \
        | jq --raw-output '.available_phone_numbers[].phone_number' | head -n ${2:-1})

We do a similar curl request for TollFree numbers. Instead of specifying InRegion= as above, we're specifying AreaCode=.

declare -a AREACODE=( 833 844 855 866 877 888 )
    RAND=$(( RANDOM % 6 ))
    RANDOM_AREACODE=${AREACODE[${RAND:-4}]}
    PHONE_LIST=$(curl --silent https://$SW_SPACE_URL/api/laml/2010-04-01/Accounts/$SW_PROJ_KEY/AvailablePhoneNumbers/US/TollFree.json \
         -X GET \
         -d "AreaCode=$RANDOM_AREACODE" \
         -u "$SW_PROJ_KEY:$SW_TOKEN" \
        | jq --raw-output '.available_phone_numbers[].phone_number' | head -n ${2:-1})

​​​​​​In the purchase function, because SignalWire returns a list of 50 numbers at a time, we need to refresh our list when it is exhausted, hence the sub-loop, until total numbers have been reached. Numbers are purchased individually in the inner-loop's curl request, and the list is refreshed with a new area code in the outer-loop's callback to sw_bulk_number_available $TYPE $ATOTAL.

while [ $t -lt $TOTAL ]; do
    sw_bulk_number_available $TYPE $ATOTAL
    while read -r PHONE; do
        if  [ $ACTION != dry ]; then
        printf "$p: puchased $PHONE\n"
        curl https://$SW_SPACE_URL/api/laml/2010-04-01/Accounts/$SW_PROJ_KEY/IncomingPhoneNumbers.json \
             -X POST \
             --data-urlencode "PhoneNumber=$PHONE" \
             -u "$SW_PROJ_KEY:$SW_TOKEN"
        else
        printf "$p: $PHONE from ${RANDOM_REGION:-$RANDOM_AREACODE} is available\n"
        fi
        p=$[$p+1]
    done < <(printf '%s\n' "$PHONE_LIST")
    t=$[$t+$ATOTAL]
    done

This script can be used to purchase any total of numbers up to the bounds of your account permissions. Please use the script with care. Alterations and abuse may cost you considerably. SignalWire will not be liable for costs incurred by misuse of this script.

By default, if you blindly blast your way through the defaults with the Enter key, the script will do a "dry" run, only listing the available numbers, and only 1 number, from 1 area code at that. This gives you the chance to tinker with the nuances of the script when raising quantities. You'll have to type "purchase" to actually make a purchase. See notes inside scripts for usage.

Python

What do I need to run this code?

You must have the SignalWire Python SDK installed. You can install that HERE

What variables change?

account - Your project ID is an alphanumeric string that tells the SignalWire SDK where to find your project. You can find this in an easily copyable format by going to your
SignalWire Portal and clicking the API tab on the left hand side.

token - Your Auth Token is an alphanumeric string that helps to authenticate your HTTP requests to SignalWire. You can create this (if you haven’t already) or copy this in an easily copyable format by going to your SignalWire Portal and clicking the API tab. If you have not created an API token, press the blue new button. If you have, click show and copy the string.

space - Your space URL is the domain of your space, i.e. example.signalwire.com. This can also be found in an easily copyable format within the API tab in your SignalWire space.

Code Walkthrough

Load the necessary libraries

# Load the SignalWire Rest Client
from signalwire.rest import Client as signalwire_client
import os

Instantiate the SignalWire Rest Client

In order for us to connect to SignalWire later on in the code using the Rest Client we first need to make sure we update space, project, and token variables.

# TODO: Update with your own credentials
account = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" 
token = "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
space = "example.signalwire.com"

client = signalwire_client(
                        account, 
                        token, 
                        signalwire_space_url = space)

if space == "example.signalwire.com" or account == "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" or token == "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX":
    print("ERROR: Please change the SW_SPACE, SW_PROJ_KEY, and SW_TOKEN variables with your actual info and re-run the program\n")
    exit()

Create purchase_menu function

This function will receive the list of available numbers and ask the user how many should be purchased. Prior to actually purchasing the numbers, we ask the user to confirm the purchase.

def purchase_menu(available_phone_numbers):
    for number_data in available_phone_numbers:
        print(number_data.phone_number)

    print('There are ' + str(len(available_phone_numbers)) + ' numbers that fit this criteria. \n')

    print('How many numbers would you like to purchase? ')
    amount_to_purchase = int(input())

    numbers_to_purchase = available_phone_numbers[:amount_to_purchase]

    os.system('cls' if os.name == 'nt' else 'clear')

    if amount_to_purchase <= 0:
        main_menu()
        exit()

    print("Numbers about to be purchased: ")

    for number_data in numbers_to_purchase:
        print(number_data.phone_number)

    print('\nWould you like to proceed with purchasing these numbers? (Y / N): ')
    purchase = input()

    if purchase == "Y":
        purchase_numbers(numbers_to_purchase)
    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        main_menu()
        exit()

Create purchase_numbers function

This function get the list of numbers to purchase, and iterates through it to make requests to actually purchase the phone numbers.

def purchase_numbers(numbers_to_purchase):
    for number_data in numbers_to_purchase:
        try:
            client.incoming_phone_numbers.create(
                                                    phone_number = number_data.phone_number
                                                )
            print(number_data.phone_number + " purchased successfully!")
        except Exception as e:
            print("ERROR: " + str(e))

Create main_menu function and run it

The main_menu function asks the user to pick the type of number to purchase. If the user chooses to purchase local numbers we give the option of restricting the search by State, Area Code, or even by a specific sequence. If the user chooses to purchase toll free numbers we give the option of restricting by area code or specific sequence only, since the State does not apply.

Lastly, we call the main_menu function to start the execution of the code.

def main_menu():
    print('Yo OG, please type in \'Local\' for Local numbers or \'TF\' for Toll Free (Local / TF): ')
    number_type = input()

    if number_type == "Local":
        print('Please enter State to search by State, Area to search by 3 digit area code, or R for random area code? (State / Area / R): ')
        state_or_area = input()

        state_choice = ""
        area_choice = ""
        substring_choice = ""

        if state_or_area == "State":
            print('Please choose a State to purchase from: \n AL AK AZ AR CA CO CT DE FL GA \n HI ID IL IN IA KS KY LA ME MD \n MA MI MN MS MO MT NE NV NJ NM \n NY NC ND OH OK OR PA RI SC SD \n TN TX UT VA WA WV WI WY: ')
            state_choice = input()
        elif state_or_area == "Area":
            print('Please enter in the 3 digit area code:')
            area_choice = input()

        print('Please choose any specific number sequence or a phrase you would like the numbers to have: ')
        substring_choice = input()

        try:
            available_phone_numbers = client.available_phone_numbers("US") \
                                            .local \
                                            .list(
                                                in_region = state_choice, 
                                                area_code = area_choice, 
                                                contains = substring_choice )

            purchase_menu(available_phone_numbers)
        except Exception as e:
            print("ERROR: " + str(e))

    elif number_type == "TF":
        tf_area = ""
        substring_choice = ""

        print('Would you like to pick a specific Area Code? If not, press Enter to skip (833 844 855 866 877 888): ')
        tf_area = input()

        print('Please choose any specific number sequence or a phrase you would like the numbers to have: ')
        substring_choice = input()

        try:
            available_phone_numbers = client.available_phone_numbers("US") \
                                            .toll_free \
                                            .list(
                                                area_code = tf_area, 
                                                contains = substring_choice )

            purchase_menu(available_phone_numbers)
        except Exception as e:
            print("ERROR: " + str(e))

    else:
        os.system('cls' if os.name == 'nt' else 'clear')
        main_menu()
        exit()

main_menu()

Each one of these numbers will be added directly to your space. Give it a moment to sync up and you will see them appear in your SignalWire dashboard!

Node.js

What do I need to run this code?

We will need the following libraries (click their names to get instructions on how to install them):

How to Run Snippet?

If you save this code snippet in a file called numbersInBulk.js, for example, you then need to run:
node numbersInBulk.js.

Code Walkthrough

Load the necessary libraries

//  Install SignalWire Rest Client
import { RestClient } from '@signalwire/node'
import { exit } from 'process'
import readlineSync from 'readline-sync'

Instantiate the SignalWire Rest Client

In order for us to connect to SignalWire later on in the code using the Rest Client we first need to make sure we update space, project, and token variables.

const project = "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"
const token = "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
const space = "example.signalwire.com"

const client = new RestClient(
    project,
    token,
    { signalwireSpaceUrl: space });

if (space == "example.signalwire.com" | project == "AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE" | token == "PTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") {
    console.log("ERROR: Please change the space, project, and token variables with your actual info and re-run the program\n")
    exit();
}

Create purchaseMenu function

This function will receive the list of available numbers and ask the user how many should be purchased. Prior to actually purchasing the numbers, we ask the user to confirm the purchase.

function purchaseMenu(available_phone_numbers) {
    available_phone_numbers.forEach((numberData) => {
        console.log(numberData.phoneNumber);
    })

    console.log('There are ' + available_phone_numbers.length + ' numbers that fit this criteria. \n');

    let amount_to_purchase = readlineSync.question('How many numbers would you like to purchase? ');
    let numbers_to_purchase = available_phone_numbers.slice(0, amount_to_purchase);

    console.clear();

    if (numbers_to_purchase <= 0) {
        mainMenu();
    }

    console.log("Numbers about to be purchased: ")

    numbers_to_purchase.forEach((numberData) => {
        console.log(numberData.phoneNumber);
    });

    let purchase = readlineSync.question('\nWould you like to proceed with purchasing these numbers? (Y / N): ');

    if (purchase == "Y") {
        purchaseNumbers(numbers_to_purchase);
    } else {
        console.clear();
        mainMenu();
    }
}

Create purchaseNumbers function

This function get the list of numbers to purchase, and iterates through it to make requests to actually purchase the phone numbers.

function purchaseNumbers(numbers_to_purchase) {
    for (let numberData of numbers_to_purchase) {
        try {
            client.incomingPhoneNumbers.create({
                phoneNumber: numberData.phoneNumber
            }).then(() => {
                console.log(numberData.phoneNumber + " purchased successfully!");
            })
        } catch (error) {
            console.log('ERROR:', error);
        }
    }
}

Create mainMenu function and run it

The mainMenu function asks the user to pick the type of number to purchase. If the user chooses to purchase local numbers we give the option of restricting the search by State, Area Code, or even by a specific sequence. If the user chooses to purchase toll free numbers we give the option of restricting by area code or specific sequence only, since the State does not apply.

Lastly, we call the mainMenu function to start the execution of the code.

function mainMenu() {
    let number_type = readlineSync.question('Yo OG, please type in \'Local\' for Local numbers or \'TF\' for Toll Free (Local / TF): ');

    if (number_type == "Local") {
        let state_or_area = readlineSync.question('Please enter State to search by State, Area to search by 3 digit area code, or R for random area code? (State / Area / R): ');

        let payload = {};
        let state_choice = "";
        let area_choice = "";
        let substring_choice = ""

        if (state_or_area == "State") {
            state_choice = readlineSync.question('Please choose a State to purchase from: \n AL AK AZ AR CA CO CT DE FL GA \n HI ID IL IN IA KS KY LA ME MD \n MA MI MN MS MO MT NE NV NJ NM \n NY NC ND OH OK OR PA RI SC SD \n TN TX UT VA WA WV WI WY: ');
            payload.region = state_choice;
        } else if (state_or_area == "Area") {
            area_choice = readlineSync.question('Please enter in the 3 digit area code:');
            payload.areaCode = area_choice;
        }

        substring_choice = readlineSync.question('Please choose any specific number sequence or a phrase you would like the numbers to have: ');

        if (substring_choice != "") {
            payload.contains = substring_choice;
        }

        client.availablePhoneNumbers("US")
            .local
            .list(payload)
            .then((available_phone_numbers) => {
                purchaseMenu(available_phone_numbers);
            })

    } else if (number_type == "TF") {
        let payload = {};

        let tf_area = "";
        let substring_choice = "";

        tf_area = readlineSync.question('Would you like to pick a specific Area Code? If not, press Enter to skip (833 844 855 866 877 888): ')

        if (tf_area != "") {
            payload.areaCode = tf_area;
        }

        substring_choice = readlineSync.question('Please choose any specific number sequence or a phrase you would like the numbers to have: ');

        if (substring_choice != "") {
            payload.contains = substring_choice;
        }

        client.availablePhoneNumbers("US")
            .tollFree
            .list(payload)
            .then((available_phone_numbers) => {
                purchaseMenu(available_phone_numbers);
            })
    } else {
        console.clear();
        mainMenu();
    }
}

mainMenu();

Wrap up

We hope this article helps you purchase numbers in bulk. Simply pick your preferred language and run the recipe code to get started! In case you run into any issues, feel free to contact our amazing Support team!

Sign Up Here

If you would like to test this example out, you can create a SignalWire account and space here.

Please feel free to reach out to us on our Community Slack or create a Support ticket if you need guidance!


Did this page help you?