Quickstart: Look up operator information for a phone number using Azure Communication Services

Important

This feature of Azure Communication Services is currently in preview.

Preview APIs and SDKs are provided without a service-level agreement. We recommend that you don't use them for production workloads. Some features might not be supported, or they might have constrained capabilities.

For more information, review Supplemental Terms of Use for Microsoft Azure Previews.

Get started with the Phone Numbers client library for JavaScript to look up operator information for phone numbers, which can be used to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.

Note

Find the code for this quickstart on GitHub.

Prerequisites

Prerequisite check

In a terminal or command window, run the node --version command to check that Node.js is installed.

Setting up

To set up an environment for sending lookup queries, take the steps in the following sections.

Create a new Node.js Application

In a terminal or command window, create a new directory for your app and navigate to it.

mkdir number-lookup-quickstart && cd number-lookup-quickstart

Run npm init -y to create a package.json file with default settings.

npm init -y

Create a file called number-lookup-quickstart.js in the root of the directory you created. Add the following snippet to it:

async function main() {
    // quickstart code will here
}

main();

Install the package

Use the npm install command to install the Azure Communication Services Phone Numbers client library for JavaScript.

npm install @azure/communication-phone-numbers@1.3.0-beta.1 --save

The --save option adds the library as a dependency in your package.json file.

Code examples

Authenticate the client

Import the PhoneNumbersClient from the client library and instantiate it with your connection string, which can be acquired from an Azure Communication Services resource in the Azure portal. It's recommended to use a COMMUNICATION_SERVICES_CONNECTION_STRING environment variable to avoid putting your connection string in plain text within your code. Learn how to manage your resource's connection string.

Add the following code to the top of phone-numbers-quickstart.js:

const { PhoneNumbersClient } = require('@azure/communication-phone-numbers');

// This code retrieves your connection string from an environment variable
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];

// Instantiate the phone numbers client
const phoneNumbersClient = new PhoneNumbersClient(connectionString);

Look up operator information for a number

To search for a phone number's operator information, call searchOperatorInformation from the PhoneNumbersClient.

let results = await phoneNumbersClient.searchOperatorInformation([ "<target-phone-number>" ]);

Replace <target-phone-number> with the phone number you're looking up, usually a number you'd like to send a message to.

Warning

Provide phone numbers in E.164 international standard format, for example, +14255550123.

Use operator information

You can now use the operator information. For this quickstart guide, we can print some of the details to the console.

let operatorInfo = results.values[0];
console.log(operatorInfo.phoneNumber + " is a " + (operatorInfo.numberType ? operatorInfo.numberType : "unknown") + " number, operated by " + (operatorInfo.operatorDetails.name ? operatorInfo.operatorDetails.name : "an unknown operator"));

You may also use the operator information to determine whether to send an SMS. For more information on sending an SMS, see the SMS Quickstart.

Run the code

Run the application from your terminal or command window with the node command.

node number-lookup-quickstart.js

Sample code

You can download the sample app from GitHub.

Get started with the Phone Numbers client library for C# to look up operator information for phone numbers, which can be used to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.

Note

Find the code for this quickstart on GitHub.

Prerequisites

Prerequisite check

In a terminal or command window, run the dotnet command to check that the .NET SDK is installed.

Setting up

To set up an environment for sending lookup queries, take the steps in the following sections.

Create a new C# application

In a terminal or command window, run the dotnet new command to create a new console app with the name NumberLookupQuickstart. This command creates a simple "Hello World" C# project with a single source file, Program.cs.

dotnet new console -o NumberLookupQuickstart

Change your directory to the newly created app folder and use the dotnet build command to compile your application.

cd NumberLookupQuickstart
dotnet build

Connect to dev package feed

The public preview version of the SDK is published to a dev package feed. You can add the dev feed using the NuGet CLI, which adds it to the NuGet.Config file.

nuget sources add -Name "Azure SDK for .NET Dev Feed" -Source "https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-net/nuget/v3/index.json"

More detailed information and other options for connecting to the dev feed can be found in the contributing guide.

Install the package

While still in the application directory, install the Azure Communication Services PhoneNumbers client library for .NET package by using the following command.

dotnet add package Azure.Communication.PhoneNumbers --version 1.3.0-beta.2

Add a using directive to the top of Program.cs to include the Azure.Communication namespace.

using System;
using System.Threading.Tasks;
using Azure.Communication.PhoneNumbers;

Update Main function signature to be async.

internal class Program
{
    static async Task Main(string[] args)
    {
        ...
    }
}

Code examples

Authenticate the client

Phone Number clients can be authenticated using connection string acquired from an Azure Communication Services resource in the Azure portal. It's recommended to use a COMMUNICATION_SERVICES_CONNECTION_STRING environment variable to avoid putting your connection string in plain text within your code. Learn how to manage your resource's connection string.

// This code retrieves your connection string from an environment variable.
string? connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
  
PhoneNumbersClient client = new PhoneNumbersClient(connectionString, new PhoneNumbersClientOptions(PhoneNumbersClientOptions.ServiceVersion.V2023_05_01_Preview));

Phone Number clients can also authenticate with Azure Active Directory Authentication. With this option, AZURE_CLIENT_SECRET, AZURE_CLIENT_ID and AZURE_TENANT_ID environment variables need to be set up for authentication.

// Get an endpoint to our Azure Communication Services resource.
Uri endpoint = new Uri("<endpoint_url>");
TokenCredential tokenCredential = new DefaultAzureCredential();
client = new PhoneNumbersClient(endpoint, tokenCredential);

Look up operator information for a number

To search for a phone number's operator information, call SearchOperatorInformationAsync from the PhoneNumbersClient.

OperatorInformationResult searchResult = await client.SearchOperatorInformationAsync(new[] { "<target-phone-number>" });

Replace <target-phone-number> with the phone number you're looking up, usually a number you'd like to send a message to.

Warning

Provide phone numbers in E.164 international standard format, for example, +14255550123.

Use operator information

You can now use the operator information. For this quickstart guide, we can print some of the details to the console.

OperatorInformation operatorInformation = searchResult.Values[0];
Console.WriteLine($"{operatorInformation.PhoneNumber} is a {operatorInformation.NumberType ?? "unknown"} number, operated by {operatorInformation.OperatorDetails.Name ?? "an unknown operator"}");

You may also use the operator information to determine whether to send an SMS. For more information on sending an SMS, see the SMS Quickstart.

Run the code

Run the application from your terminal or command window with the dotnet run command.

dotnet run

Sample code

You can download the sample app from GitHub.

Get started with the Phone Numbers client library for Java to look up operator information for phone numbers, which can be used to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.

Note

Find the code for this quickstart on GitHub.

Prerequisites

Prerequisite check

In a terminal or command window, run the mvn -v command to check that Maven is installed.

Setting up

To set up an environment for sending lookup queries, take the steps in the following sections.

Create a new Java application

In a terminal or command window, navigate to the directory where you'd like to create your Java application. Run the following command to generate the Java project from the maven-archetype-quickstart template.

mvn archetype:generate -DgroupId=com.communication.lookup.quickstart -DartifactId=communication-lookup-quickstart -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

The 'generate' task creates a directory with the same name as the artifactId. Under this directory, the src/main/java directory contains the project source code, the src/test/java directory contains the test source, and the pom.xml file is the project's Project Object Model, or POM.

Connect to dev package feed

The public preview version of the SDK is published to a dev package feed. To connect to the dev feed, open the pom.xml file in your text editor and add the dev repo to both your pom.xml's <repositories> and <distributionManagement> sections

<repository>
  <id>azure-sdk-for-java</id>
  <url>https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1</url>
  <releases>
    <enabled>true</enabled>
  </releases>
  <snapshots>
    <enabled>true</enabled>
  </snapshots>
</repository>

Add or edit the settings.xml file in ${user.home}/.m2

<server>
  <id>azure-sdk-for-java</id>
  <username>azure-sdk</username>
  <password>[PERSONAL_ACCESS_TOKEN]</password>
</server>

Finally, generate a Personal Access Token with Packaging read & write scopes and paste it into the <password> tag.

More detailed information and other options for connecting to the dev feed can be found here.

Install the package

Add the following dependency elements to the group of dependencies in the pom.xml file.

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-common</artifactId>
    <version>1.0.0</version>
  </dependency>

  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-communication-phonenumbers</artifactId>
    <version>1.2.0-beta.1</version>
  </dependency>

  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.2.3</version>
  </dependency>

  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-core</artifactId>
    <version>1.41.0</version>
  </dependency>
</dependencies>

Code examples

Set up the app framework

From the project directory:

  1. Navigate to the /src/main/java/com/communication/lookup/quickstart directory
  2. Open the App.java file in your editor
  3. Replace the System.out.println("Hello world!"); statement
  4. Add import directives

Use the following code to begin:

package com.communication.lookup.quickstart;

import com.azure.communication.phonenumbers.*;
import com.azure.communication.phonenumbers.models.*;
import com.azure.core.http.rest.*;
import com.azure.core.util.Context;
import com.azure.identity.*;
import java.io.*;
import java.util.ArrayList;

public class App
{
    public static void main( String[] args ) throws IOException
    {
        System.out.println("Azure Communication Services - Number Lookup Quickstart");
        // Quickstart code goes here
    }
}

Authenticate the client

Authenticate the Phone Numbers Client

The PhoneNumberClientBuilder is enabled to use Azure Active Directory Authentication. Using the DefaultAzureCredentialBuilder is the easiest way to get started with Azure Active Directory. You can acquire your resource name from an Azure Communication Services resource in the Azure portal.

// You can find your resource name from your resource in the Azure portal
String endpoint = "https://<RESOURCE_NAME>.communication.azure.com";

PhoneNumbersClient phoneNumberClient = new PhoneNumbersClientBuilder()
    .endpoint(endpoint)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Alternatively, the client can be authenticated using a connection string, also acquired from an Azure Communication Services resource in the Azure portal. It's recommended to use a COMMUNICATION_SERVICES_CONNECTION_STRING environment variable to avoid putting your connection string in plain text within your code. Learn how to manage your resource's connection string.

// This code retrieves your connection string from an environment variable
String connectionString = System.getenv("COMMUNICATION_SERVICES_CONNECTION_STRING");

PhoneNumbersClient phoneNumberClient = new PhoneNumbersClientBuilder()
    .connectionString(connectionString)
    .buildClient();

Look up operator information for a number

To search for a phone number's operator information, call searchOperatorInformation from the PhoneNumbersClient.

ArrayList<String> phoneNumbers = new ArrayList<String>();
phoneNumbers.add("<target-phone-number>");
OperatorInformationResult result = phoneNumberClient.searchOperatorInformation(phoneNumbers);

Replace <target-phone-number> with the phone number you're looking up, usually a number you'd like to send a message to.

Warning

Provide phone numbers in E.164 international standard format, for example, +14255550123.

Use operator information

You can now use the operator information. For this quickstart guide, we can print some of the details to the console.

OperatorInformation operatorInfo = result.getValues().get(0);

String numberType = operatorInfo.getNumberType() == null ? "unknown" : operatorInfo.getNumberType().toString();
String operatorName = "an unknown operator";
if (operatorInfo.getOperatorDetails()!= null && operatorInfo.getOperatorDetails().getName() != null)
{
    operatorName = operatorInfo.getOperatorDetails().getName();
}
System.out.println(operatorInfo.getPhoneNumber() + " is a " + numberType + " number, operated by " + operatorName);

You may also use the operator information to determine whether to send an SMS. For more information on sending an SMS, see the SMS Quickstart.

Run the code

Run the application from your terminal or command window with the following commands: Navigate to the directory containing the pom.xml file and compile the project.

mvn compile

Then, build the package.

mvn package

Run the following mvn command to execute the app.

mvn exec:java -Dexec.mainClass="com.communication.lookup.quickstart.App" -Dexec.cleanupDaemonThreads=false

Sample code

You can download the sample app from GitHub.

Get started with the Phone Numbers client library for Python to look up operator information for phone numbers, which can be used to determine whether and how to communicate with that phone number. Follow these steps to install the package and look up operator information about a phone number.

Note

Find the code for this quickstart on GitHub.

Prerequisites

Prerequisite check

In a terminal or command window, run the python --version command to check that Python is installed.

Setting up

To set up an environment for sending lookup queries, take the steps in the following sections.

Create a new Python application

In a terminal or command window, create a new directory for your app and navigate to it.

mkdir number-lookup-quickstart && cd number-lookup-quickstart

Use a text editor to create a file called number_lookup_sample.py in the project root directory and add the following code. The remaining quickstart code is added in the following sections.

import os
from azure.communication.phonenumbers import PhoneNumbersClient

try:
   print('Azure Communication Services - Number Lookup Quickstart')
   # Quickstart code goes here
except Exception as ex:
   print('Exception:')
   print(ex)

Install the package

While still in the application directory, install the Azure Communication Services PhoneNumbers client library for Python package by using the pip install command.

pip install azure-communication-phonenumbers==1.2.0b1 

Code examples

Authenticate the client

The PhoneNumbersClient is enabled to use Azure Active Directory Authentication. Using the DefaultAzureCredential object is the easiest way to get started with Azure Active Directory and you can install it using the pip install command.

pip install azure-identity

Creating a DefaultAzureCredential object requires you to have AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID already set as environment variables with their corresponding values from your registered Azure AD application.

For a quick ramp-up on how to get these environment variables, you can follow the Set up service principals from CLI quickstart.

Once you have installed the azure-identity library, we can continue authenticating the client.

from azure.identity import DefaultAzureCredential

# You can find your endpoint from your resource in the Azure portal
endpoint = 'https://<RESOURCE_NAME>.communication.azure.com'
try:
    print('Azure Communication Services - Number Lookup Quickstart')
    credential = DefaultAzureCredential()
    phone_numbers_client = PhoneNumbersClient(endpoint, credential)
except Exception as ex:
    print('Exception:')
    print(ex)

Alternatively, the client can be authenticated using a connection string, also acquired from an Azure Communication Services resource in the Azure portal. It's recommended to use a COMMUNICATION_SERVICES_CONNECTION_STRING environment variable to avoid putting your connection string in plain text within your code. Learn how to manage your resource's connection string.

# This code retrieves your connection string from an environment variable
connection_string = os.getenv('COMMUNICATION_SERVICES_CONNECTION_STRING')
try:
    print('Azure Communication Services - Number Lookup Quickstart')
    phone_numbers_client = PhoneNumbersClient.from_connection_string(connection_string)
except Exception as ex:
    print('Exception:')
    print(ex)

Look up operator information for a number

To search for a phone number's operator information, call search_operator_information from the PhoneNumbersClient.

results = phone_numbers_client.search_operator_information("<target-phone-number>")

Replace <target-phone-number> with the phone number you're looking up, usually a number you'd like to send a message to.

Warning

Provide phone numbers in E.164 international standard format, for example, +14255550123.

Use operator information

You can now use the operator information. For this quickstart guide, we can print some of the details to the console.

operator_information = results.values[0]

number_type = operator_information.number_type if operator_information.number_type else "unknown"
if operator_information.operator_details is None or operator_information.operator_details.name is None:
    operator_name = "an unknown operator"
else:
    operator_name = operator_information.operator_details.name

print(str.format("{0} is a {1} number operated by {2}", operator_information.phone_number, number_type, operator_name))

You may also use the operator information to determine whether to send an SMS. For more information on sending an SMS, see the SMS Quickstart.

Run the code

Run the application from your terminal or command window with the python command.

python number_lookup_sample.py

Sample code

You can download the sample app from GitHub.

Troubleshooting

Common questions and issues:

  • The data returned by this endpoint is subject to various international laws and regulations, therefore the accuracy of the results depends on several factors. These factors include whether the number has been ported, the country code, and the approval status of the caller. Based on these factors, operator information may not be available for some phone numbers or may reflect the original operator of the phone number, not the current operator.

Next steps

In this quickstart you learned how to:

  • Look up operator information for a phone number