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:
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.
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:
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());
}
}
package voice;
import com.sinch.sdk.domains.voice.api.v1.*;
import com.sinch.sdk.domains.voice.models.v1.*;
import com.sinch.sdk.domains.voice.models.requests.*;
public class Snippet {
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.";
CalloutRequestTTS parameters =
CalloutRequestTTS.builder()
.setDestination(DestinationPstn.from(phoneNumber))
.setText(message)
.build();
String callId = calloutsService.textToSpeech(parameters);
return callId;
}
}
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.
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().v1().[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().v1().callouts()
voice().v1().calls()
voice().v1().conferences()
voice().v1().applications()
For example:
var response = client.voice()
.v1()
.callouts()
.textToSpeech(CalloutRequestTTS
.builder()
.setDestination(DestinationPstn.from(phoneNumber))
.setText("Thank you for calling Sinch. This call will now end.")
.build());
voice().v1().callouts()
endpoint category
The voice().v1().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 operation | SDK method | JavaDocs entry |
---|---|---|
Makes a Text-to-speech callout | textToSpeech() | textToSpeech |
Makes a Conference callout | conference() | conference |
Makes a Custom callout | Custom() | custom |
voice().v1().calls()
endpoint category
The voice().v1().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 operation | SDK method | JavaDocs entry |
---|---|---|
Get information about a call | get() | get |
Manage call with callLeg | manageWithCallLeg() | manageWithCallLeg |
Updates a call in progress | update() | update |
voice().v1().conferences()
endpoint category
The voice().v1().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 operation | SDK method | JavaDocs entry |
---|---|---|
Makes a conference callout | call() | call |
Get information about a conference | get() | get |
Manage a conference participant | manageParticipant() | manageParticipant |
Remove a participant from a conference | kickParticipant() | kickParticipant |
Remove all participants from a conference | kickAll() | kickAll |
voice().v1().applications()
endpoint category
The voice().v1().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 operation | SDK method | JavaDocs entry |
---|---|---|
Return all the numbers assigned to an application | listNumbers() | listNumbers |
Assign a number or list of numbers to an application | assignNumbers() | assignNumbers |
Unassign a number from an application | unassignNumber() | unassignNumber |
Return the callback URLs for an application | getCallbackUrls() | getCallbackUrls |
Update the callback URL for an application | updateCallbackUrls() | updateCallbackUrls |
Returns information about a number | queryNumber() | queryNumber |
voice().v1().webhooks()
endpoint category
The voice().v1().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 method | Description | JavaDocs entry |
---|---|---|
validateAuthenticatedHeader() | 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. | validateAuthenticationHeader |
serializeResponse() | Serializes a SvamlControl response into a JSON string. You must serialize the response before returning it because the Sinch servers expect a JSON response. | serializeResponse |
parseEvent() | Deserializes a JSON response into a VoiceWebhookEvent event class. You can use this method to handle different event types and write logic for different events. | parseEvent |
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(phoneNumber))
.setText("Thank you for calling Sinch. This call will now end.")
.build()
{
"method": "ttsCallout",
"ttsCallout": {
"destination": {
"type": "number",
"endpoint": "YOUR_phone_number"
},
"text": "Thank you for calling Sinch. This call will now end."
}
}
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.