Sinch Java SDK for SMS

The Sinch SMS Java SDK allows you to quickly interact with the SMS 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 SMS API are structured similarly to those that are sent and received using the SMS API itself.

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 on the side of this page is an example of how to use the Java SDK to send an SMS message. The code is also displayed below, along with a SMS API call that accomplishes the same task, for reference:

REST APISDK
Copy
Copied
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 <YOUR_TOKEN_HERE>")
      .build();

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

    System.out.println(response.body());
  }
}
Copy
Copied
package sms;

import com.sinch.sdk.domains.sms.*;
import com.sinch.sdk.domains.sms.models.*;
import com.sinch.sdk.domains.sms.models.requests.*;
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("Sending SMS Text");
    BatchText value =
        batchesService.send(
            SendSmsBatchTextRequest.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.

This example highlights the following required to successfully make an SMS 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 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:

Copy
Copied
package sms.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)
                                  .setSmsRegion(SMSRegion.US)
                                  .build());
}
Note:
The above sample specifies the US region. If you want to specify the European region, you can use .setSmsRegion(SMSRegion.EU).

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

Copy
Copied
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:
API operationSDK methodJavaDocs
Sendsend()send
List batcheslist()list
Dry rundryRun()dryRun
Get a batch messageget()get
Update a batch messageupdate()update
Replace a batchreplace()replace
Cancel a batch messagecancel()cancel
Send delivery feedback for a messagesendDeliveryFeedback()sendDeliveryFeedback

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:
API operationSDK methodJavaDocs
Retrieve a delivery reportget()get
Retrieve a recipient delivery reportgetForNumber()getForNumber
Retrieve a list of delivery reportslist()list

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:
API operationSDK methodJavaDocs
List groupslist()list
Create a groupcreate()create
Retrieve a groupget()get
Update a groupupdate()update
Replace a groupreplace()replace
Delete a groupdelete()delete
List group member phone numberslistMembers()listMembers

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:

SDKJSON
Copy
Copied
DeliveryReportType.FULL
Copy
Copied
"delivery_report": "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:

SDKJSON
Copy
Copied
SendSmsBatchTextRequest.builder()
                    .setTo(Collections.singletonList("YOUR_recipient_phone_number"))
                    .setBody("Test message using Java SDK")
                    .setFrom("YOUR_sinch_phone_number")
                    .setDeliveryReport(DeliveryReportType.NONE)
                    .build()
Copy
Copied
{
"from": "YOUR_Sinch_number",
"to": [
"YOUR_number"
],
"body": "Hello from Sinch!",
"delivery_report": "none",
"type": "mt_text"
}
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.

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