Skip to content
Last updated

Click to view on Community.

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:

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. 
package numbers;

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.AvailableNumberListRequest;
import com.sinch.sdk.domains.numbers.models.v1.response.AvailableNumberListResponse;
import java.util.logging.Logger;

public class Snippet {

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

  static void execute(NumbersService numbersService) {

    String regionCode = "US";
    NumberType type = NumberType.LOCAL;

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

    LOGGER.info(
        String.format("Listing available number type '%s' for region '%s'", type, regionCode));

    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:

  • numbers().v1()
  • numbers().v1().regions()
  • numbers().v1().callbackConfiguration()
  • numbers().v1().webhooks()

For example:

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

The field mappings are described in the sections below.

numbers().v1() endpoint category

The numbers().v1() category of the Java SDK has methods that correspond to the available and active endpoints. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:

numbers().v1().regions() endpoint category

The numbers().v1().regions() category of the Java SDK corresponds to the availableRegions endpoint. The mapping between the API operation and corresponding Java method are described below, as well as links to the JavaDocs page:

API operationSDK methodJavaDocs
List available regionslist()list

numbers().v1().callbackConfiguration() endpoint category

The numbers().v1().callbackConfiguration() category of the Java SDK corresponds to the callbackConfiguration endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:

API operationSDK methodJavaDocs
Get callbacks configurationget()get
Update callback configurationupdate()update

numbers().v1().webhooks() endpoint category

The numbers().v1().webhooks() category of the Java SDK corresponds to the Event notification operation. The mapping between the API operation and corresponding Java method are described below, as well as links to the JavaDocs page:

API operationSDK methodJavaDocs
Event notificationparseEvent()parseEvent

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:

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 SMS configuration objects below. One is represented in JSON, the other as a Java object:

AvailableNumberListRequest.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 from = "YOUR_sinch_phone_number";
    String recipient = "YOUR_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(from)
                .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.

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:

  • groups()
  • batches()
  • inbounds()
  • deliveryReports()

For example:

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

The field mappings are described in the sections below.

sms().batches() endpoint category

The sms().batches() category of the Java SDK corresponds to the batches endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:

sms().deliveryReports() endpoint category

The sms().deliveryReports() category of the Java SDK corresponds to the delivery_report and delivery_reports endpoints. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:

sms().groups() endpoint category

The sms().groups() category of the Java SDK corresponds to the groups endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:

sms().inbounds() endpoint category

The sms().inbounds() category of the Java SDK corresponds to the inbounds endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:

API operationSDK methodJavaDocs
List incoming messageslist()list
Retrieve inbound messageget()get

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:

SendSmsBatchTextRequest.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.

send-message.js
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.*;
import com.sinch.sdk.domains.conversation.models.v1.messages.*;
import com.sinch.sdk.domains.conversation.models.v1.messages.request.*;
import com.sinch.sdk.domains.conversation.models.v1.messages.response.SendMessageResponse;
import com.sinch.sdk.domains.conversation.models.v1.messages.types.text.*;
import java.util.*;
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 = "YOUR_app_id";
    String from = "YOUR_sms_sender";
    String to = "RECIPIENT_number";

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

    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(smsSender, from))
            .build();

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

    SendMessageResponse value = messagesService.sendMessage(request);

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

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:

  • v1().messages()
  • v1().app()
  • v1().contact()
  • v1().events()
  • v1().transcoding()
  • v1().capability()
  • templates.v1().templates()
  • templates.v2().templates()
  • v1().webhooks()
  • v1().conversation()

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());

conversation().v1().messages endpoint category

The messages category of the Java SDK corresponds to the messages endpoint. The mapping between the API operations and corresponding methods are described below:

conversation().v1().app() endpoint category

The app category of the Java SDK corresponds to the apps endpoint. The mapping between the API operations and corresponding methods are described below:

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.

conversation().v1().contact() endpoint category

The contact category of the Java SDK corresponds to the contacts endpoint. The mapping between the API operations and corresponding methods are described below:

conversation().v1().conversations() endpoint category

The conversations category of the Java SDK corresponds to the conversations endpoint. The mapping between the API operations and corresponding methods are described below:

conversation().v1().events() endpoint category

The events category of the Java SDK corresponds to the events endpoint. The mapping between the API operations and corresponding methods are described below:

conversation().v1().transcoding() endpoint category

The transcoding category of the Java SDK corresponds to the messages:transcode endpoint. The mapping between the API operations and corresponding methods are described below:

conversation().v1().capability() endpoint category

The capability category of the Java SDK corresponds to the capability endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Capability lookuplookup

conversation().v1().webhooks() endpoint category

The webhooks category of the Java SDK corresponds to the webhooks endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
List webhookslist
Create a new webhookcreate
Get a webhookget
Update an existing webhookupdate
Delete an existing webhookdelete
No corresponding operation. You can use this function to authenticate information received from payloads. This function takes the secret parameter, which is the Secret token to be used to validate the received request.validateAuthenticationHeader
No corresponding operation. You can use this function to deserialize payloads received from callbacks. This function takes the jsonPayload parameter, which is the received payload.parseEvent

conversation().templates().v1().templates() endpoint category

The templates (version 1) category of the Java SDK corresponds to the Templates endpoint. The mapping between the API operations and corresponding methods are described below:

conversation().templates().v2().templates() endpoint category

The templates (version 2) category of the Java SDK corresponds to the Templates-V2 endpoint. The mapping between the API operations and corresponding methods are described below:

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
package voice;

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

public class Snippet {

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

  public static String execute(VoiceService voiceService) {

    CalloutsService calloutsService = voiceService.callouts();

    String phoneNumber = "YOUR_phone_number";
    String message = "Hello, this is a call from Sinch. Congratulations! You made your first call.";

    LOGGER.info("Calling '" + phoneNumber + '"');

    CalloutRequestTTS parameters =
        CalloutRequestTTS.builder()
            .setDestination(DestinationPstn.from(phoneNumber))
            .setText(message)
            .build();

    String callId = calloutsService.textToSpeech(parameters);

    LOGGER.info("Call started with id: '" + callId + '"');

    return callId;
  }
}

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:

  • voice().callouts()
  • voice().calls()
  • voice().conferences()
  • voice().applications()

For example:

var response = client.voice()
                    .callouts()
                    .textToSpeech(CalloutRequestParametersTTS
                                .builder()
                                .setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
                                .setText("Thank you for calling Sinch. This call will now end.")
                                .build());

voice().callouts() endpoint category

The voice().callouts() category of the Java SDK corresponds corresponds to the callouts endpoint. The mapping between the API operations and corresponding Java methods are described below:

API operationSDK methodJavaDocs entry
Makes a Text-to-speech callouttextToSpeech()textToSpeech
Makes a Conference calloutconference()conference
Makes a Custom calloutCustom()custom

voice().calls() endpoint category

The voice().calls() category of the Java SDK corresponds corresponds to the calls endpoint. The mapping between the API operations and corresponding Java methods are described below:

voice().conferences() endpoint category

The voice().conferences() category of the Java SDK corresponds corresponds to the conferences endpoint. The mapping between the API operations and corresponding Java methods are described below:

voice().applications() endpoint category

The voice().applications() category of the Java SDK corresponds corresponds to the configuration endpoint. The mapping between the API operations and corresponding Java methods are described below:

voice().webhooks() endpoint category

The voice().webhooks() category of the Java SDK are helper methods designed to assist in serializing/deserializing requests from and responses to the Sinch servers, as well as validate that the requests coming from the Sinch servers are authentic.

SDK methodDescriptionJavaDocs entry
validateAuthenticatedRequest()Validates if the request is authentic. It is a best practice to evaluate if a request is authentic before performing any business logic on it.validateAuthenticatedRequest
serializeVerificationResponse()Serializes a SVAMLControl response into a JSON string. You must serialize the response before returning it because the Sinch servers expect a JSON response.serializeWebhooksResponse
unserializeVerificationEvent()Deserializes a JSON response into a Voice event class. You can use this method to handle different event types and write logic for different events.unserializeWebhooksEvent

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:

CalloutRequestParametersTTS.builder()
                          .setDestination(DestinationNumber.valueOf("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.js
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(
      VerificationStartService 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 service
   * @param code Code received by SMS
   * @param id Verification ID related to the verification
   */
  private void reportSmsVerification(VerificationReportService 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:

  • verification().v1().verificationStart()
  • verification().v1().verificationReport()
  • verification().v1().verificationStatus()
  • verification().v1().webhooks()

For example:

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

The field mappings are described in the sections below.

verification().v1().verificationStart() endpoint category

The verification().v1().verificationStart() category of the Java SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Java methods are described below:

verification().v1().verificationReport() endpoint category

The verification().v1().verificationReport() category of the Java SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Java methods are described below:

verification().v1().verificationStatus() endpoint category

The verification().v1().verificationStatus() category of the Java SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Java methods are described below:

verification().v1().webhooks() endpoint category

The verification().v1().webhooks() category of the Java SDK corresponds to the callbacks section. The mapping between the API operations and corresponding Java methods are described below:

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 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.