Skip to main content

Deleting All Number Assignments from Multiple Campaigns

Overview

This snippet will show how you can easily use our Delete Phone Number Assignments Endpoint to remove all of the phone number assignments from multiple campaigns. This frees up the numbers to be used in any other campaigns or for use cases other than 10DLC messaging. You only need a CSV with multiple campaign SIDs to get started!

This script will only remove number assignments from a campaign - it will not remove from the account!

If you need to remove numbers entirely from your SignalWire space, check out our guide on Releasing Numbers.

What do I need to run this code?

The API requires that you authenticate yourself using your Project ID, API Token, and Space URL. If you do not know where to find these values, check out our guide here!

You will also need a CSV containing campaign SIDs in the first column. You can name the column headers anything you want but if the SID is not in the first column, you will need to adjust the code.

CampaignSID,CampaignID
60a12b34-6aaa-4aaa-baaa-7aaaaaaaaaaa,C123XXX
60a12b34-6aaa-4aaa-baaa-7aaaaaaaaaaa,C234XXX

Your campaign SIDs can be found in your portal under Messaging Campaigns -> Campaigns or by listing campaigns using our endpoint.

Step by Step Code Walkthrough

The first step is always to import our required libraries/packages and assign the necessary authentication variables to be used later. We will be using requests and requests.auth to handle our HTTP requests with ease as well as csv! We will also create an empty list to store the campaign SIDs that we get from our csv file.

import requests
import csv
from requests.auth import HTTPBasicAuth

# assign client variables
SpaceURL = 'EXAMPLE.signalwire.com'
projectID = ""
authToken = ""
host = f"https://{SpaceURL}"
campaigns = []

Next, we will use csv to read in our CSV file of campaign SIDs and add them to our campaigns list.

# read in campaigns CSV
with open("Campaigns.csv", 'r', encoding='utf-8-sig') as csvfile:
reader = csv.reader(csvfile)
next(reader, None)
for row in reader:
campaigns.append(row[0])

In the next section, we will loop through the campaign SIDs in campaigns one at a time. For each campaign, we will list all of the numbers assigned to the campaign using the List Number Assignments endpoint and store the JSON data returned from the API in campaignNumbers.

Completed vs Pending numbers

Listing all numbers will return both completed and pending number assignments, but number assignments cannot be deleted by API unless they are completed. If you need pending number assignments deleted, you can do this within your portal or reach out to SignalWire Support!

for campaign in campaigns:
print(f"Starting campaign {campaign} now")

# List All Campaign Numbers
url = f"https://{SpaceURL}/api/relay/rest/registry/beta/campaigns/{campaign}/numbers"
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'])

We have now arrived at the final step! We will loop through the JSON data returned via the API and store the assignment SID, number SID, and the number itself in the variables assignmentSID, numberSID, and tn. We will then try to release the number using assignmentSID and either print that the number was successful or print the error code and the reason it was not successful.

# delete listed numbers
for number in campaignNumbers:
tn = number['phone_number']['number']
numberSID = number['phone_number']['id']
assignmentSID = number['id']

try:
url = f"https://{SpaceURL}/api/relay/rest/registry/beta/numbers/{assignmentSID}"
payload = {}
headers = {}
response = requests.request("DELETE", url, headers=headers, data=payload,
auth=HTTPBasicAuth(projectID, authToken))
if response.ok:
print(f"{tn} successfully deleted")
else:
print(f"{response.status_code} {response.text}. {tn} not deleted.")

except Exception as e:
print(f"Error: {str(e)}")

Wrap up

Keeping your brands/campaigns clean and up to date is very important to stay in compliance with all of the latest 10DLC requirements that The Campaign Registry has dictated. This script will let you remove all numbers from multiple campaigns quickly so that you don't have to go through them all one by one by hand.

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!