Skip to main content

Deleting All Number Assignments from a Campaign

Overview

This snippet will show how you can easily use our Delete Phone Number Assignments Endpoint to remove all of the phone number assignments in one of your messaging campaigns! This frees up the numbers to be used in any other campaigns or for use cases other than 10DLC messaging.

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 to Releasing Numbers.

Full code example: Removing Number Assignments from a Campaign
import requests
from requests.auth import HTTPBasicAuth

SpaceURL = 'EXAMPLE.signalwire.com'
projectID = ""
authToken = ""
campaignID = ""
host = f"https://{SpaceURL}"

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'])

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)}")

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 your campaign SID which can be found in your portal under Messaging Campaigns -> Campaigns or by listing campaigns using our endpoint.

A screenshot of the Campaigns page within the Messaging Campaigns section of a SignalWire Space. Campaign details, including the campaign SID, are available on this page.

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!

import requests
from requests.auth import HTTPBasicAuth

# assign auth variables to be used later
SpaceURL = 'EXAMPLE.signalwire.com'
projectID = ""
authToken = ""
campaignID = ""
host = f"https://{SpaceURL}"

Next, 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!

# List All Campaign Numbers
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'])

We have now arrived at the third and 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.

# loop through numbers and call delete number function on each
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

That's all there is to it! Any time you need to remove the numbers on a campaign, you can revisit this script to accomplish the task quickly and painlessly.

Sign Up Here

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

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