📌 Listing Phone Numbers Assigned to One Campaign - Python & Node.js

Overview

If you have a lot of campaigns, it's important to keep track of what phone numbers belong to each campaign. You can always compare this list to your account numbers to get an accurate idea of which numbers are registered and which aren't! To list your account numbers, check out our guide here!

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

You will need your API credentials as well as the campaign ID that you would like to pull information on. You can find your API credentials in the API tab of your SignalWire Space!

You can find your campaign ID by going to the Messaging Campaigns section of your SignalWire space and clicking the specific campaign whose numbers you need. The ID is the long alphanumeric string at the top as shown here:

Python

What do I need to run this code?

For the following code to work, you will need to have pandas and requests installed.

Read about the different ways to install pandas here.

Read about requests and how to install using pip here.

How to Run Snippet?

If you copy the code and save it to a file named listCampaignNumbers.py, for example, to run it you will need to run:

  • MacOS/Linux - python3 listCampaignNumbers.py
  • Windows - py listCampaignNumbers.py

Code Walkthrough

Load necessary libraries and set up SignalWire client variables

This application is very simple! We will first define our SpaceURL, projectID, authToken, and campaignID variables to be used throughout the code.

import pandas as pd
import requests
from requests.auth import HTTPBasicAuth

# assign client variables
SpaceURL = 'example.signalwire.com'
projectID = ""
authToken = ""
campaignID = ""
host = f"https://{SpaceURL}"

Get the list of numbers

Next, we need to define our URL for the API endpoint and create an HTTP request to it using the Python requests library. However, this URL will only return 1000 results at a time. If you have less than 1000 results, then you have nothing to worry about! However, we will use the while loop in the next section to take care of campaigns with more than 1000 numbers. We will paginate through the API results and continually add the results to campaignNumbers.

# define URL for API Endpoint
url = f"https://{SpaceURL}/api/relay/rest/registry/beta/campaigns/{campaignID}/numbers?page_size=1000"
payload={}
headers = {}

response = requests.request("GET", url, headers=headers, data=payload, auth=HTTPBasicAuth(projectID, authToken)).json()
campaignNumbers = response['data']

while "next" in response['links'].keys():
     response = requests.get(host + response['links']['next'], auth=HTTPBasicAuth(projectID, authToken)).json()
     campaignNumbers.extend(response['data'])
print(f"There are {len(campaignNumbers)} total numbers in campaign {campaignID}.")

Create a DataFrame, print it, and export to CSV

Lastly, we will append each phone number to our d list and export to CSV using the Pandas library!

# Sets up an empty array
d = []

# loop through numbers
for number in campaignNumbers:
      d.append(number['phone_number']['number'])
df = pd.DataFrame(d, columns=(['Phone Number']))

print(df)
# Exports dataframe to csv, index=False turns off the indexing for each row
df.to_csv('CompanyNumbers.csv', index=False, encoding='utf-8')

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):

  • Danfo.js
  • fs - there is no need to install this module, as it is part of the Node.js Core
  • node-fetch

How to Run Snippet?

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

Code Walkthrough

Load the necessary libraries

import dfd from "danfojs";
import fs from "fs";
import fetch from "node-fetch";

Prepare your SignalWire client variables

In order for us to connect to SignalWire later on in the code we first need to make sure we update spaceURL, projectID, authToken, and campaignID.

// TODO: Update with your own credentials
const spaceURL = 'YOURSPACE.signalwire.com';
const projectID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
const authToken = "PTxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const campaignID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";

const host = "https://" + spaceURL;
const authenticationString = projectID + ":" + authToken;

Prepare function to get the data

Here we prepare the getDatafunction, taking pagination into account.

var allData = [];

async function getData(url) {
    const options = {
        method: 'GET',
        headers: {
            'Authorization': 'Basic ' + new Buffer.from(authenticationString).toString('base64')
        }
    };

    const response = await fetch(url, options).then(res => res.json())

    response.data.forEach((record) => {
        allData.push(record);
    })

    if (response.links.next) {
        let newURL = host + response.links.next;
        return await getData(newURL);
    }
}

Get the list of numbers associated with the campaign

In this step we connect to the List all Phone Number Assignments endpoint and add each number to the numbers array.

let url = "https://" + spaceURL + "/api/relay/rest/registry/beta/campaigns/" + campaignID + "/numbers?page_size=1000";
await getData(url)

console.log("There are", allData.length, "total numbers in campaign", campaignID + ".")

let numbers = [];

allData.forEach((record) => {
    numbers.push([record.phone_number.number]);
})

Create DataFrame, print it, and export to CSV

Here we create the finalData DataFrame from the numbers array we created in the previous step. It then makes printing the results to the terminal as well as exporting to CSV very easy.

let finalData = new dfd.DataFrame(numbers, {
    columns: ["Phone Number"],
    config: {
        tableDisplayConfig: {
            columns: [
                { width: 1 },
                { width: 14 }
            ],
        },
    },
});

finalData.print();
fs.writeFileSync("CampaignNumbers.csv", dfd.toCSV(finalData));

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?