Telephony API

Buy phone numbers via an API

The Sonetel API allows you to instantly buy phone numbers in any country and city of choice.

Phone numbers purchased via the API receive a $1 discount on the monthly renewal fee. This means that phone numbers cost from $0.79 per month.

 

How to buy a phone number via the API

This is how it works.

  1. Supported countries
    Get a list of the countries where phone numbers can be purchased.
  2. See supported number types and number availability
    Get a list of all area codes and number types in a specific country (city area codes, toll free, national, mobile numbers etc.) and the quantity of phone numbers that are available per city and prefix.
  3. See available numbers
    Get a list of phone numbers available for ordering, of the specified type in the selected country.
  4. Buy a number
    Buy a number and have it added to your account.

In the next step you can configure the call forwarding of your new phone number.

If your account is verified, and the phone number selected isn’t subject to specific activation restrictions – the number will become activated instantly.

 

Buying a phone number with Python

A sample script for buying phone number with Python can be found here. The script can be used after finding an available number for purchasing.

The script starts by importing the necessary modules, and then defines the phone number to be purchased and the base URL of the Sonetel API.

Next, it sets the access token for the API and decodes it to get the account ID of the user. It then constructs the request headers and sends an HTTP POST request to the /account/{account_id}/phonenumbersubscription endpoint of the Sonetel API, passing the phone number and the access token in the request body and headers, respectively.

If the request is successful, the response is printed to the console. Otherwise, an error is raised.

To use the script, you will need to enter your own access token and the phone number you want to purchase. You can obtain the access token by following the instructions in the documentation at https://docs.sonetel.com.

The following Python script can be used to purchase a new phone number.

import json
import requests
import jwt

# Number to purchase
phnum = "ENTER_PHONE_NUMBER"

base_url = "https://public-api.sonetel.com/"

#  API Access token
access_token = "ENTER_ACCESS_TOKEN"
decoded_token = jwt.decode(
    access_token,
    audience='api.sonetel.com',
    options={"verify_signature": False}
    )
acc_id = decoded_token['acc_id']

# Request headers
headers = {
    "Authorization": "Bearer {}".format(access_token),
    'Content-Type': 'application/json'
    }

# Purchase phone number
response = requests.request(
    "POST",
    '{}account/{}/phonenumbersubscription'.format(base_url,acc_id),
    headers=headers,
    data=json.dumps({"phnum": phnum}), timeout=60)

response.raise_for_status()

if response.ok:
    print(response.json())

 

Buying a phone number with NodeJS

A sample script for buying phone number with NodeJS can be found here. The script can be used after finding an available number for purchasing.

The NodeJS module exports a function called buyPhoneNumber. This function can be used to purchase a phone number using the Sonetel API. The function accepts two arguments:

  1. accessToken: The access token to authorize the request with Sonetel’s API.
  2. numToPurchase: The phone number to purchase, in the E164 format (without the leading “+”).

The function starts by checking that the accessToken and numToPurchase arguments are provided. If either is missing, an error is thrown. The access token is then decoded and the account ID is extracted.

Next, the function constructs an HTTP POST request to the /account/{account_id}/phonenumbersubscription endpoint of the Sonetel API, passing the phone number and access token in the request body and headers, respectively. The response is handled asynchronously and, if it is successful, the response data is logged to the console. Otherwise, an error is thrown.

To use the function, you will need to import it into your script and call it with your own access token and the phone number you want to purchase. You can obtain the access token by following the instructions here.

The following NodeJS script can be used to purchase a new phone number.

import http from 'https';

export const buyPhoneNumber = (accessToken, numToPurchase) => {

  const host = process.env.SonetelAPIName ?? 'public-api.sonetel.com';

  // Check if the access token and the number to purchase were passed.
  // If not, throw an error.
  if (!accessToken){
    throw Error('accessToken must be defined')
  }
  if (!numToPurchase){
    throw Error('numToPurchase must be defined')
  }

  const parsedToken = JSON.parse(Buffer.from(accessToken.split('.')[1], 'base64').toString());
  const accountId = parsedToken.acc_id;

  const options = {
    hostname: host,
    path: `/account/${accountId}/phonenumbersubscription`,
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${accessToken}`,
      "Accept": "application/json"
    }
  }
  const req = http.request(options, (res) => {
    const { statusCode } = res;
    if (statusCode !== 200){
      throw new Error(`Request failed. Status code ${statusCode}`);
    }
    res.setEncoding('utf-8');
    let rawData = '';
    res.on('data', (chunk) => rawData += chunk );
    res.on('end',() => {
      try {
        const parsedData = JSON.parse(rawData);
        console.log(parsedData);
      } catch (e) {
        console.error(e.message);
      }
    })
  });

  req.on('error', (e) => {
    throw new Error(`Request failed. ${e.message}`);
  });

  req.write(JSON.stringify({ phnum: numToPurchase }));
  req.end();

}