Skip to content
Last updated

Java SDK

The Sinch Java SDK allows you to quickly interact with the suite of Sinch APIs from inside your Java applications. When using the Java SDK, the code representing requests and queries sent to and responses received from the suite of Sinch APIs are structured similarly to those that are sent and received using the suite of Sinch APIs.

Important Java SDK links:

The following links are available for your reference:

Client

When using the Sinch Java SDK, you initialize communication with the Sinch backend by initializing the Java SDK's main client class. This client allows you to access the functionality of the Sinch Java SDK.

Initialization

Initialization of the Java SDK client class can be done in two ways, depending on which product you are using.

Unified Project Authentication

To successfully initialize the Sinch client class, you must provide a valid access key ID and access key secret combination. You must also provide your Project ID. For example:


package numbers.sdk;

import com.sinch.sdk.SinchClient;

public class App {
    
    public static String access_key = "YOUR_access_key";
    public static String access_secret = "YOUR_access_secret";
    public static String project_id = "YOUR_project_id"

    public static void main(String[] args) {
        
      SinchClient client = new SinchClient(Configuration.builder()
                                  .setKeyId(access_key)
                                  .setKeySecret(access_secret)
                                  .setProjectId(project_id)
                                  .build());
}

Application Authentication

To start using the SDK, you need to initialize the main client class and create a configuration object to connect to your Sinch account and Voice app. You can find all of the credentials you need on your Sinch dashboard.

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.models.Configuration;

public class App {
    
    public static void main(String[] args) {
        SinchClient client = new SinchClient(Configuration.builder()
                                    .setApplicationKey("YOUR_application_key")
                                    .setApplicationSecret("YOUR_application_secret")
                                    .build());
    }
}
Note

For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials.

Domains

The Java SDK currently supports the following products:

Numbers Domain

Note:

This guide describes the syntactical structure of the Java SDK for the Numbers API, including any differences that may exist between the API itself and the SDK. For a full reference on Numbers API calls and responses, see the Numbers API Reference.

This code sample is an example of how to use the Java SDK to list the available numbers of a given type and region. We've also provided an example that accomplishes the same task using the REST API.

Snippet.java
// This code returns a list of all the available numbers for a given set of search criteria. 
/**
 * Sinch Java Snippet
 *
 * <p>This snippet is available at https://github.com/sinch/sinch-sdk-java
 *
 * <p>See https://github.com/sinch/sinch-sdk-java/blob/main/examples/snippets/README.md for details
 */
package numbers;

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.domains.numbers.api.v1.NumbersService;
import com.sinch.sdk.domains.numbers.models.v1.NumberType;
import com.sinch.sdk.domains.numbers.models.v1.request.AvailableNumbersListQueryParameters;
import com.sinch.sdk.domains.numbers.models.v1.response.AvailableNumberListResponse;
import com.sinch.sdk.models.Configuration;
import java.util.logging.Logger;
import utils.Settings;

public class SearchForAvailableNumbers {

  private static final Logger LOGGER = Logger.getLogger(SearchForAvailableNumbers.class.getName());

  public static void main(String[] args) {

    String projectId = Settings.getProjectId().orElse("MY_PROJECT_ID");
    String keyId = Settings.getKeyId().orElse("MY_KEY_ID");
    String keySecret = Settings.getKeySecret().orElse("MY_KEY_SECRET");

    // ISO 3166-1 alpha-2 country code of the phone number. e.g. "US", "GB", "SE"...
    // See https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 for details
    String regionCode = "MY_REGION_CODE";
    NumberType type = NumberType.LOCAL;

    Configuration configuration =
        Configuration.builder()
            .setProjectId(projectId)
            .setKeyId(keyId)
            .setKeySecret(keySecret)
            .build();

    SinchClient client = new SinchClient(configuration);

    NumbersService numbersService = client.numbers().v1();

    AvailableNumbersListQueryParameters parameters =
        AvailableNumbersListQueryParameters.builder()
            .setRegionCode(regionCode)
            .setType(type)
            .build();

    LOGGER.info("Looking for available numbers");

    AvailableNumberListResponse response = numbersService.searchForAvailableNumbers(parameters);

    response
        .iterator()
        .forEachRemaining(
            number -> LOGGER.info(String.format("Available number details: %s", number)));
  }
}

The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.numbers().v1().[endpoint_category()].[method()].

Endpoint categories

In the Sinch Java SDK, Numbers API endpoints are accessible through the client:

For example:

var numbers = client.numbers().v1().list(ActiveNumbersListQueryParameters.builder()
                                                                .setType(NumberType.LOCAL)
                                                                .setRegionCode("US")
                                                                .build());

Request and query parameters

Requests and queries made using the Java SDK are similar to those made using the Numbers API. Many of the fields are named and structured similarly. For example, consider the representations of a MOBILE number type. One field is represented in JSON, and the other is using our Java SDK:

NumberType.MOBILE

Many fields in the Java SDK are rendered as enums in data models.

Nested objects

When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the Numbers configuration objects below. One is represented in JSON, the other as a Java object:

AvailableNumberListQueryParameters.builder()
                        .setType(NumberType.LOCAL)
                        .setRegionCode("US")
                        .build()
{
  "type": "LOCAL",
  "regionCode": "US"
}

Note that in the Java SDK you would use a builder() method to construct the appropriate data model in the correct structure.

Responses

Response fields match the API responses. They are delivered as Java objects.

SMS Domain

Note:

This guide describes the syntactical structure of the Java SDK for the SMS API, including any differences that may exist between the API itself and the SDK. For a full reference on SMS API calls and responses, see the SMS API Reference.

The code sample below is an example of how to use the Java SDK to send an SMS message. We've also provided an example that accomplishes the same task using the REST API.

App.java
//Use this code to send an SMS message. 
package sms;

import com.sinch.sdk.domains.sms.api.v1.BatchesService;
import com.sinch.sdk.domains.sms.api.v1.SMSService;
import com.sinch.sdk.domains.sms.models.v1.batches.request.TextRequest;
import com.sinch.sdk.domains.sms.models.v1.batches.response.BatchResponse;
import java.util.Collections;
import java.util.logging.Logger;

public class Snippet {

  private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());

  static void execute(SMSService smsService) {

    BatchesService batchesService = smsService.batches();

    String sender = "SENDER_NUMBER";
    String recipient = "RECIPIENT_PHONE_NUMBER";
    String body = "This is a test SMS message using the Sinch Java SDK.";

    LOGGER.info(String.format("Submitting batch to send SMS to '%s'", recipient));

    BatchResponse value =
        batchesService.send(
            TextRequest.builder()
                .setTo(Collections.singletonList(recipient))
                .setBody(body)
                .setFrom(sender)
                .build());

    LOGGER.info("Response: " + value);
  }
}

Note that the REST API uses the Service Plan ID and and API token instead of Project ID and access keys.

SMS Region

When using the SMS domain, the SmsRegion is a required parameter.

SinchClient client = new SinchClient(Configuration.builder()
                                  .setKeyId(access_key)
                                  .setKeySecret(access_secret)
                                  .setProjectId(project_id)
                                  .setSmsRegion(SMSRegion.US)
                                  .build());

The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.sms.[endpoint_category()].[method()].

Endpoint categories

In the Sinch Java SDK, SMS API endpoints are accessible through the client. The naming convention of the endpoints in the SDK resembles the API:

For example:

var batches = client.sms().batches().list(ListBatchesQueryParameters.builder()
                                                .setPage(1)
                                                .setPageSize(10)
                                                .setFrom("YOUR_from_number")
                                                .setStartDate(Instant.from("2023-11-01T00:00:00.00"))
                                                .setEndDate(Instant.from("2023-11-30T00:00:00.00"))
                                                .setClientReference("YOUR_reference")
                                                .build());

Request and query parameters

Requests and queries made using the Java SDK are similar to those made using the SMS API. Many of the fields are named and structured similarly. For example, consider the representations of an SMS API message type. One field is represented in JSON, and the other is using our Java SDK:

DeliveryReportType.FULL

Many fields in the Java SDK are rendered as enums in data models.

Nested objects

When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the SMS configuration objects below. One is represented in JSON, the other as a Java object:

TextRequest.builder()
                    .setTo(Collections.singletonList("YOUR_recipient_phone_number"))
                    .setBody("Test message using Java SDK")
                    .setFrom("YOUR_sinch_phone_number")
                    .setDeliveryReport(DeliveryReportType.NONE)
                    .build()

Note that in the Java SDK you would use a builder() method to construct the appropriate data model in the correct structure. Note also that while in the raw JSON request body you can specify the message type, the Java SDK has a specific Batch request object for each message type.

Responses

Response fields match the API responses. They are delivered as Java objects.

Conversation Domain

Note:

This guide describes the syntactical structure of the Java SDK for the Conversation API, including any differences that may exist between the API itself and the SDK. For a full reference on Conversation API calls and responses, see the Conversation REST API Reference.

The code sample below is an example of how to use the Java SDK to send a text message on the SMS channel of a Conversation API app. We've also provided an example that accomplishes the same task using the REST API.

App.java
package conversation;

import com.sinch.sdk.domains.conversation.api.v1.ConversationService;
import com.sinch.sdk.domains.conversation.api.v1.MessagesService;
import com.sinch.sdk.domains.conversation.models.v1.ChannelRecipientIdentities;
import com.sinch.sdk.domains.conversation.models.v1.ChannelRecipientIdentity;
import com.sinch.sdk.domains.conversation.models.v1.ConversationChannel;
import com.sinch.sdk.domains.conversation.models.v1.messages.AppMessage;
import com.sinch.sdk.domains.conversation.models.v1.messages.request.SendMessageRequest;
import com.sinch.sdk.domains.conversation.models.v1.messages.response.SendMessageResponse;
import com.sinch.sdk.domains.conversation.models.v1.messages.types.text.TextMessage;
import java.util.Collections;
import java.util.logging.Logger;

public class Snippet {

  private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());

  static void execute(ConversationService conversationService) {

    MessagesService messagesService = conversationService.messages();

    String appId = "CONVERSATION_APPLICATION_ID";
    String from = "SINCH_VIRTUAL_PHONE_NUMBER";
    String to = "RECIPIENT_PHONE_NUMBER";

    String body = "This is a test Conversation message using the Sinch Java SDK.";

    ChannelRecipientIdentities recipients =
        ChannelRecipientIdentities.of(
            ChannelRecipientIdentity.builder()
                .setChannel(ConversationChannel.SMS)
                .setIdentity(to)
                .build());

    AppMessage<TextMessage> message =
        AppMessage.<TextMessage>builder()
            .setBody(TextMessage.builder().setText(body).build())
            .build();

    SendMessageRequest<TextMessage> request =
        SendMessageRequest.<TextMessage>builder()
            .setAppId(appId)
            .setRecipient(recipients)
            .setMessage(message)
            .setChannelProperties(Collections.singletonMap("SMS_SENDER", from))
            .build();

    LOGGER.info("Sending SMS Text using Conversation API");

    SendMessageResponse value = messagesService.sendMessage(request);

    LOGGER.info("Response: " + value);
  }
}
Note:

When using the Conversation domain, the ConversationRegion parameter is required.

SinchClient client = new SinchClient(Configuration.builder()
                                  .setKeyId(access_key)
                                  .setKeySecret(access_secret)
                                  .setProjectId(project_id)
                                  .setConversationRegion(ConversationRegion.US)
                                  .build());

The above sample is configured for the US region. If you want to specify the European region, you can use .setConversationRegion(ConversationRegion.EU). If you want to specify the Brazil region, you can use .setConversationRegion(ConversationRegion.BR).

The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.conversation().v1().[endpoint_category()].[method()] or client.conversation().templates().[templates_version()].[method()].

Endpoint categories

In the Sinch Java SDK, Conversation API endpoints are accessible through the client (either a general client or a Conversation-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

The `ConversationChannelCredentialsBuilderFactory` class

This class will help you define channel credentials when creating or updating an app. Each channel is represented by a corresponding method, and invoking that method will allows you to more easily determine the information that is required to create the credentials.

For example:

SendMessageResponse response =
    client.conversation().v1().messages().sendMessage(SendMessageRequest.<TextMessage>builder()
        .setAppId("YOUR_app_id")
        .setRecipient(ChannelRecipientIdentities.of(ChannelRecipientIdentity.builder().setChannel(ConversationChannel.SMS).setIdentity("RECIPIENT_number").build()))
        .setMessage(AppMessage.<TextMessage>builder().setBody(TextMessage.builder().setText("This is a test Conversation message using the Sinch Java SDK.").build()).build())
        .setChannelProperties(Collections.singletonMap("SMS_SENDER", "YOUR_sms_sender"))
        .build());

Request and query parameters

Requests and queries made using the Java SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. For example, consider the representation of a Conversation API channel. One field is represented in our Java SDK, and the other is using the REST API:

ConversationChannel.SMS

Note that the fields have similar names, and many fields in the Java SDK are rendered as enums in data models.

Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding method. For example, consider this example in which the get method of messages is invoked:


var response = client.conversation().v1().messages().get("YOUR_message_id", "CONVERSATION_SOURCE");

When using the Conversation API, message_id would be included as a path parameter, and messages_source would be included as a query parameter in the JSON payload. With the Java SDK, both parameters are included as arguments in the get method.

Responses

Response fields match the API responses. They are delivered as Java objects.

Voice Domain

Note

This guide describes the syntactical structure of the Java SDK for the Voice API, including any differences that may exist between the API itself and the SDK. For a full reference on Voice API calls and responses, see the Voice API Reference.

The code sample below is an example of how to use the Java SDK to make a text to speech phone call to phone number using the Java SDK and the Voice API. We've also provided an example that accomplishes the same task using the REST API.

Snippet.java
/**
 * Sinch Java Snippet
 *
 * <p>This snippet is available at https://github.com/sinch/sinch-sdk-java
 *
 * <p>See https://github.com/sinch/sinch-sdk-java/blob/main/examples/snippets/README.md for details
 */
package voice.callouts;

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.domains.voice.api.v1.CalloutsService;
import com.sinch.sdk.domains.voice.models.v1.callouts.request.CalloutRequestTTS;
import com.sinch.sdk.domains.voice.models.v1.destination.DestinationPstn;
import com.sinch.sdk.models.Configuration;
import java.util.logging.Logger;
import utils.Settings;

public class Call {

  private static final Logger LOGGER = Logger.getLogger(Call.class.getName());

  public static void main(String[] args) {

    String applicationKey = Settings.getApplicationKey().orElse("MY_APPLICATION_KEY");
    String applicationSecret = Settings.getApplicationSecret().orElse("MY_APPLICATION_SECRET");

    // The phone number you want to call, in E.164 format (e.g., +12025550123)
    String recipientPhoneNumber = "RECIPIENT_PHONE_NUMBER";
    String textToSpeech = "Hello, this is a call initiated from Sinch Java SDK. Goodbye.";

    Configuration configuration =
        Configuration.builder()
            .setApplicationKey(applicationKey)
            .setApplicationSecret(applicationSecret)
            .build();

    SinchClient client = new SinchClient(configuration);

    CalloutsService calloutsService = client.voice().v1().callouts();

    LOGGER.info(String.format("Calling phone number '%s'", recipientPhoneNumber));

    CalloutRequestTTS request =
        CalloutRequestTTS.builder()
            .setDestination(DestinationPstn.from(recipientPhoneNumber))
            .setText(textToSpeech)
            .build();

    String response = calloutsService.call(request);

    LOGGER.info("Response: " + response);
  }
}

The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.voice().[endpoint_category()].[method()].

Endpoint categories

In the Sinch Java SDK, Voice API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

var response = client.voice()
                    .v1()
                    .callouts()
                    .textToSpeech(CalloutRequestTTS
                                .builder()
                                .setDestination(DestinationPstn.from("YOUR_phone_number"))
                                .setText("Thank you for calling Sinch. This call will now end.")
                                .build());

Request and query parameters

Requests and queries made using the Java SDK are similar to those made using the Voice API. Many of the fields are named and structured similarly.

Many fields in the Java SDK are rendered as enums in data models.

Nested objects

When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the Voice configuration objects below. One is represented in JSON, the other as a Java object:

CalloutRequestTTS.builder()
                 .setDestination(DestinationPstn.from("YOUR_phone_number"))
                 .setText("Thank you for calling Sinch. This call will now end.")
                 .build()

Note that in the Java SDK you would use a specific helper class for the type of Voice call you want to make and a builder() method to construct the appropriate data model in the correct structure.

Responses

Response fields match the API responses. They are delivered as Java objects.

Verification Domain

Note:

This guide describes the syntactical structure of the Java SDK for the Verification API, including any differences that may exist between the API itself and the SDK. For a full reference on Verification API calls and responses, see the Verification API Reference.

The code sample below is an example of how to use the Java SDK to initiate an SMS PIN Verification. We've also provided an example that accomplishes the same task using the REST API.

VerificationsSample.java
package verification;

import com.sinch.sdk.core.exceptions.ApiException;
import com.sinch.sdk.core.utils.StringUtil;
import com.sinch.sdk.domains.verification.api.v1.*;
import com.sinch.sdk.domains.verification.models.v1.NumberIdentity;
import com.sinch.sdk.domains.verification.models.v1.report.request.VerificationReportRequestSms;
import com.sinch.sdk.domains.verification.models.v1.report.response.VerificationReportResponseSms;
import com.sinch.sdk.domains.verification.models.v1.start.request.VerificationStartRequestSms;
import com.sinch.sdk.domains.verification.models.v1.start.response.VerificationStartResponseSms;
import com.sinch.sdk.models.E164PhoneNumber;
import java.util.Scanner;

public class VerificationsSample {

  private final VerificationService verificationService;

  public VerificationsSample(VerificationService verificationService) {
    this.verificationService = verificationService;
  }

  public void start() {

    E164PhoneNumber e164Number = promptPhoneNumber();

    try {
      // Starting verification onto phone number
      String id = startSmsVerification(verificationService.verificationStart(), e164Number);

      // Ask user for received code
      Integer code = promptSmsCode();

      // Submit the verification report
      reportSmsVerification(verificationService.verificationReport(), code, id);
    } catch (ApiException e) {
      echo("Error (%d): %s", e.getCode(), e.getMessage());
    }
  }

  /**
   * Will start an SMS verification onto specified phone number
   *
   * @param service Verification Start service
   * @param phoneNumber Destination phone number
   * @return Verification ID
   */
  private String startSmsVerification(
      VerificationsStartService service, E164PhoneNumber phoneNumber) {

    echo("Sending verification request onto '%s'", phoneNumber.stringValue());

    VerificationStartRequestSms parameters =
        VerificationStartRequestSms.builder()
            .setIdentity(NumberIdentity.valueOf(phoneNumber))
            .build();

    VerificationStartResponseSms response = service.startSms(parameters);
    echo("Verification started with ID '%s'", response.getId());
    return response.getId();
  }

  /**
   * Will use Sinch product to retrieve verification report by ID
   *
   * @param service Verification Report service
   * @param code Code received by SMS
   * @param id Verification ID related to the verification
   */
  private void reportSmsVerification(VerificationsReportService service, Integer code, String id) {

    VerificationReportRequestSms parameters =
        VerificationReportRequestSms.builder().setCode(String.valueOf(code)).build();

    echo("Requesting report for '%s'", id);
    VerificationReportResponseSms response = service.reportSmsById(id, parameters);
    echo("Report response: %s", response);
  }

  /**
   * Prompt user for a valid phone number
   *
   * @return Phone number value
   */
  private E164PhoneNumber promptPhoneNumber() {
    String input;
    boolean valid;
    do {
      input = prompt("\nEnter a phone number to start verification");
      valid = E164PhoneNumber.validate(input);
      if (!valid) {
        echo("Invalid number '%s'", input);
      }
    } while (!valid);

    return E164PhoneNumber.valueOf(input);
  }

  /**
   * Prompt user for a SMS code
   *
   * @return Value entered by user
   */
  private Integer promptSmsCode() {
    Integer code = null;
    do {
      String input = prompt("Enter the verification code to report the verification");
      try {
        code = Integer.valueOf(input);
      } catch (NumberFormatException nfe) {
        echo("Invalid value '%s' (code should be numeric)", input);
      }

    } while (null == code);
    return code;
  }

  /**
   * Endless loop for user input until a valid string is entered or 'Q' to quit
   *
   * @param prompt Prompt to be used task user a value
   * @return The entered text from user
   */
  private String prompt(String prompt) {

    String input = null;
    Scanner scanner = new Scanner(System.in);

    while (StringUtil.isEmpty(input)) {
      System.out.println(prompt + " ([Q] to quit): ");
      input = scanner.nextLine();
    }

    if ("Q".equalsIgnoreCase(input)) {
      System.out.println("Quit application");
      System.exit(0);
    }
    return input.trim();
  }

  private void echo(String text, Object... args) {
    System.out.println("  " + String.format(text, args));
  }
}

The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.verification().v1().[endpoint_category()].[method()].

Endpoint categories

In the Sinch Java SDK, Verification API endpoints are accessible through the client. The naming convention of the endpoints represented in the SDK matches the API:

For example:

var identity = NumberIdentity.valueOf("YOUR_phone_number");
var response = client.verification().v1().verificationStart().startSms(VerificationStartRequestSms
                                        .builder()
                                        .setIdentity(identity)
                                        .build());

Request and query parameters

Requests and queries made using the Java SDK are similar to those made using the Verification API. Many of the fields are named and structured similarly. For example, consider the representations of a Verification method type. One field is represented in JSON, and the other is using our Java SDK:

VerificationStartRequestSms

Many fields in the Java SDK are rendered as enums in data models.

Nested objects

When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the Verification configuration objects below. One is represented in JSON, the other as a Java object:

VerificationStartRequestSms.builder()
                                .setIdentity(NumberIdentity.builder()
                                    .setEndpoint("YOUR_phone_number")
                                    .build())
                                .build()
{
  "method": "sms",
  "identity": {
    "type": "number",
    "endpoint": "YOUR_phone_number"
  }
}

Note that in the Java SDK you would use a specific helper class for the type of Verification you want to send and a builder() method to construct the appropriate data model in the correct structure.

Responses

Response fields match the API responses. They are delivered as Java objects.