Sinch Java SDK for Voice

The Sinch Voice Java SDK allows you to quickly interact with the Voice API from inside your Java applications. The fastest way to get started with the SDK is to check out our getting started guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK.

Note:
You can also view the generated JavaDocs for the Java SDK here.

Syntax

When using the Java SDK, the code representing requests and queries sent to and responses received from the Voice API are structured similarly to those that are sent and received using the Voice API itself.

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.

App.java

This code makes a text to speech phone call using the Java SDK.

package voice.make.call;

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.models.Configuration;
import com.sinch.sdk.domains.voice.models.DestinationNumber;
import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersTTS;

import java.io.IOException;
import java.util.logging.Logger;

public class App {

    private static final Logger LOGGER = Logger.getLogger(App.class.getName());
    
    public void makeCall() {
        SinchClient client = new SinchClient(Configuration.builder()
                                            .setApplicationKey("YOUR_application_key")
                                            .setApplicationSecret("YOUR_application_secret")
                                            .build());
        
        var response = client.voice().callouts().textToSpeech(CalloutRequestParametersTTS.builder()
                                                            .setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
                                                            .setText("Hello, this is a call from Sinch. Congratulations! You made your first call.")
                                                            .build());
        
        LOGGER.info("Response: " + response);
    }

    public App() throws IOException {}

    public static void main(String[] args) {
        try {
            new App().makeCall();
        } catch (Exception e) {
            LOGGER.severe(e.getMessage());
            e.printStackTrace();
        }
    }
}

The code sample on the side of this page 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. The code is also displayed below, along with a REST API call that accomplishes the same task, for reference:

REST APISDK
Copy
Copied
package app;

import java.net.*;
import java.net.http.*;
import java.util.*;

public class App {
  private static final String key = "";
  private static final String secret = "";
  private static final String fromNumber = "";
  private static final String to = "";
  private static final String locale = "";

  public static void main(String[] args) throws Exception {
    var httpClient = HttpClient.newBuilder().build();

    var payload = String.join("\n"
      , "{"
      , " \"method\": \"ttsCallout\","
      , " \"ttsCallout\": {"
      , "  \"cli\": \"" + fromNumber + "\","
      , "  \"destination\": {"
      , "   \"type\": \"number\","
      , "   \"endpoint\": \"" + to + "\""
      , "  },"
      , "  \"locale\": \"" + locale + "\","
      , "  \"text\": \"Hello, this is a call from Sinch. Congratulations! You made your first call.\""
      , " }"
      , "}"
    );

    var host = "https://calling.api.sinch.com";
    var pathname = "/calling/v1/callouts";
    var request = HttpRequest.newBuilder()
      .POST(HttpRequest.BodyPublishers.ofString(payload))
      .uri(URI.create(host + pathname ))
      .header("Content-Type", "application/json")
      .header("Authorization", "Basic " + Base64.getEncoder().encodeToString((key + ":" + secret).getBytes()))
      .build();

    var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
  }
}
Copy
Copied
package voice.make.call;

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.models.Configuration;
import com.sinch.sdk.domains.voice.models.DestinationNumber;
import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersTTS;

import java.io.IOException;
import java.util.logging.Logger;

public class App {

    private static final Logger LOGGER = Logger.getLogger(App.class.getName());
    
    public void makeCall() {
        SinchClient client = new SinchClient(Configuration.builder()
                                            .setApplicationKey("YOUR_application_key")
                                            .setApplicationSecret("YOUR_application_secret")
                                            .build());
        
        var response = client.voice()
                            .callouts()
                            .textToSpeech(CalloutRequestParametersTTS
                                                        .builder()
                                                        .setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
                                                        .setText("Hello, this is a call from Sinch. Congratulations! You made your first call.")
                                                        .build());
        
        LOGGER.info("Response: " + response);
    }

    public App() throws IOException {}

    public static void main(String[] args) {
        try {
            new App().makeCall();
        } catch (Exception e) {
            LOGGER.severe(e.getMessage());
            e.printStackTrace();
        }
    }
}

This example highlights the following required to successfully make a Voice API call using the Sinch Java SDK:

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

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.

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

Voice domain

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:

Copy
Copied
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:
API operationSDK methodJavaDocs entry
Get information about a callget()get
Manage call with callLegmanageWithCallLeg()manageWithCallLeg
Updates a call in progressupdate()update

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:
API operationSDK methodJavaDocs entry
Makes a conference calloutcall()call
Get information about a conferenceget()get
Manage a conference participantmanageParticipant()manageParticipant
Remove a participant from a conferencekickParticipant()kickParticipant
Remove all participants from a conferencekickAll()kickAll

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:
API operationSDK methodJavaDocs entry
Return all the numbers assigned to an applicationlistNumbers()listNumbers
Assign a number or list of numbers to an applicationassignNumbers()assignNumbers
Unassign a number from an applicationunassignNumber()unassignNumber
Return the callback URLs for an applicationgetCallbackUrls()getCallbackUrls
Update the callback URL for an applicationupdateCallbackUrls()updateCallbackUrls
Returns information about a numberqueryNumber()queryNumber

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:

SDKJSON
Copy
Copied
CalloutRequestParametersTTS.builder()
                            .setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
                            .setText("Thank you for calling Sinch. This call will now end.")
                            .build()
Copy
Copied
{
  "method": "ttsCallout",
  "ttsCallout": {
    "destination": {
      "type": "number",
      "endpoint": "YOUR_phone_number"
    },
    "text": "Thank you for calling Sinch. This call will now end."
  }
}
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.

We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.

App.java

This code makes a text to speech phone call using the Java SDK.

package voice.make.call;

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.models.Configuration;
import com.sinch.sdk.domains.voice.models.DestinationNumber;
import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersTTS;

import java.io.IOException;
import java.util.logging.Logger;

public class App {

    private static final Logger LOGGER = Logger.getLogger(App.class.getName());
    
    public void makeCall() {
        SinchClient client = new SinchClient(Configuration.builder()
                                            .setApplicationKey("YOUR_application_key")
                                            .setApplicationSecret("YOUR_application_secret")
                                            .build());
        
        var response = client.voice().callouts().textToSpeech(CalloutRequestParametersTTS.builder()
                                                            .setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
                                                            .setText("Hello, this is a call from Sinch. Congratulations! You made your first call.")
                                                            .build());
        
        LOGGER.info("Response: " + response);
    }

    public App() throws IOException {}

    public static void main(String[] args) {
        try {
            new App().makeCall();
        } catch (Exception e) {
            LOGGER.severe(e.getMessage());
            e.printStackTrace();
        }
    }
}