# Java SDK
The Sinch Java SDK allows you to quickly interact with the from inside your Java applications. When using the Java SDK, the code representing requests and queries sent to and responses received from the are structured similarly to those that are sent and received using the .
Important Java SDK links:
The following links are available for your reference:
- [Sinch Java SDK repository](https://github.com/sinch/sinch-sdk-java)
- [Sinch Java SDK releases](https://github.com/sinch/sinch-sdk-java/releases)
- [Sinch Java SDK examples](https://github.com/sinch/sinch-sdk-java/tree/main/examples)
- Generated [JavaDocs](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/)
## Installation
The easiest way to install the SDK is using the Maven central repository. You can create your Java project using your favorite method. Once your project is created, you need to add the SDK as a dependency. Add the following to the `pom.xml` file:
```xml
This snippet is available at https://github.com/sinch/sinch-sdk-java * *
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)));
}
}
REST API
```java
import java.net.*;
import java.net.http.*;
import java.util.*;
public class App {
public static void main(String[] args) throws Exception {
var httpClient = HttpClient.newBuilder().build();
var host = "https://numbers.api.sinch.com";
var projectId = "YOUR_projectId";
var pathname = "/v1/projects/" + projectId + "/availableNumbers";
var request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(host + pathname ))
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("YOUR_username:YOUR_password").getBytes()))
.build();
var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
```
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()]`.
In the Sinch Java SDK, Numbers API endpoints are accessible through the client:
- [`numbers().v1()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/numbers/api/v1/package-summary.html)
- [`numbers().v1().regions()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/numbers/api/v1/AvailableRegionsService.html)
- [`numbers().v1().eventDestinations()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/numbers/api/v1/EventDestinationsService.html)
- [`numbers().v1().sinchEvents()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/numbers/api/v1/SinchEventsService.html)
For example:
```java
var numbers = client.numbers().v1().list(ActiveNumbersListQueryParameters.builder()
.setType(NumberType.LOCAL)
.setRegionCode("US")
.build());
```
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:
SDK
```java
NumberType.MOBILE
```
REST API
```JSON
"type": "MOBILE"
```
Many fields in the Java SDK are rendered as enums in data models.
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:
```Java
AvailableNumberListQueryParameters.builder()
.setType(NumberType.LOCAL)
.setRegionCode("US")
.build()
```
```JSON
{
"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.
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](/docs/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.
SDK
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);
}
}
REST API
```java
package send.sms;
import java.net.*;
import java.net.http.*;
import java.util.*;
public class App {
public static void main(String[] args) throws Exception {
var httpClient = HttpClient.newBuilder().build();
var payload = String.join("\n"
, "{"
, " \"from\": \"YOUR_Sinch_virtual_number\","
, " \"to\": ["
, " \"YOUR_recipient_number\""
, " ],"
, " \"body\": \"YOUR_message_body\","
, " \"delivery_report\": \"summary\","
, " \"type\": \"mt_text\""
, "}"
);
var host = "https://";
var servicePlanId = "YOUR_service_plan_id_PARAMETER";
var region = "us";
var pathname = region + ".sms.api.sinch.com/xms/v1/" + servicePlanId + "/batches";
var request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(payload))
.uri(URI.create(host + pathname ))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer This snippet is available at https://github.com/sinch/sinch-sdk-java
*
* 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);
}
}
REST API
App.java
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());
}
}
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()]`.
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()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/voice/api/v1/CalloutsService.html)
- [`voice().v1().calls()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/voice/api/v1/CallsService.html)
- [`voice().v1().conferences()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/voice/api/v1/ConferencesService.html)
- [`voice().v1().applications()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/voice/api/v1/ApplicationsService.html)
- [`voice().v1().sinchEvents()`](https://www.javadoc.io/doc/com.sinch.sdk/sinch-sdk-java/latest/com/sinch/sdk/domains/voice/api/v1/SinchEventsService.html)
For example:
```java
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());
```
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.
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:
SDK
```Java
CalloutRequestTTS.builder()
.setDestination(DestinationPstn.from("YOUR_phone_number"))
.setText("Thank you for calling Sinch. This call will now end.")
.build()
```
JSON
```JSON
{
"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.
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](/docs/verification/api-reference/verification).
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.
SDK
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));
}
}
REST API
```java
package app;
import java.io.IOException;
import java.net.*;
import java.net.http.*;
import java.util.*;
public class App {
private static final String applicationKey = "