Sinch Java SDK for Conversation

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

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

Copy
Copied
// Find your App ID at dashboard.sinch.com/convapi/apps
// Find your Project ID at dashboard.sinch.com/settings/project-management
// Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys
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"
      , "{"
      , " \"app_id\": \"{APP_ID}\","
      , " \"recipient\": {"
      , "  \"identified_by\": {"
      , "   \"channel_identities\": ["
      , "    {"
      , "     \"channel\": \"{CHANNEL}\","
      , "     \"identity\": \"{IDENTITY}\""
      , "    }"
      , "   ]"
      , "  }"
      , " },"
      , " \"message\": {"
      , "  \"text_message\": {"
      , "   \"text\": \"This is a text message.\""
      , "  }"
      , " }"
      , "}"
    );

    var host = "https://{region}.conversation.api.sinch.com";
    var projectId = "YOUR_project_id_PARAMETER";
    var region = "us";
    var pathname = "/v1/projects/%7Bproject_id%7D/messages:send";
    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(("<username>:<password>").getBytes()))
      .build();

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

    System.out.println(response.body());
  }
}

This example highlights the following required to successfully make a Conversation 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 conversation.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());
}
Note:
The above sample defaults to the US region. If you want to specify the European region, you can use .setConversationRegion(ConversationRegion.EU). If you want to specify the Brazil region, you can use .setConversationRegion(ConversationRegion.BR). If you want to re-specify the US region, you can use setConversationRegion(ConversationRegion.US).

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

Copy
Copied
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:
API operationSDK method
Send a messagesendMessage, or you could use any of the following message-specific methods:
sendCardMessage
sendCarouselMessage
sendChoiceMessage
sendContactInfoMessage
sendListMessage
sendLocationMessage
sendMediaMessage
sendTemplateMessage
sendTextMessage
Get a messageget
Delete a messagedelete
List messageslist
Update a message's metadataupdate

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:
API operationSDK method
List all apps for a given projectlist
Create an appcreate
Get an appget
Delete an appdelete
Update an appupdate

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:
API operationSDK method
List contactslist
Create a contactcreate
Get a contactget
Delete a contactdelete
Update a contactupdate
Merge two contactsmergeContact
Get channel profilegetChannelProfileByContactId or getChannelProfileByChannelIdentity

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:
API operationSDK method
List conversationslist
Create a conversationcreate
Get a conversationget
Delete a conversationdelete
Update a conversationupdate
Stop conversationstopActive
Inject a messageinjectMessage
Inject an eventinjectEvent
List recent conversationslistRecent

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:
API operationSDK method
Send an eventsend
Get an eventget
Delete an eventdelete
List eventslist

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:
API operationSDK method
Transcode a messagetranscodeMessage

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:
API operationSDK method
List all templates belonging to a project IDlist
Creates a templatecreate
Updates a templateupdate
Get a templateget
Delete a templatedelete

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:
API operationSDK method
List all templates belonging to a project IDlist
Creates a templatecreate
Lists translations for a templatelistTranslations
Updates a templateupdate
Get a templateget
Delete a templatedelete

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:

SDKREST API
Copy
Copied
ConversationChannel.SMS
Copy
Copied
"     \"channel\": \"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:
SDKREST API
Copy
Copied
var response = client.conversation().v1().messages().get("YOUR_message_id", "CONVERSATION_SOURCE");
Copy
Copied
var host = "https://{region}.conversation.api.sinch.com";
var projectId = "YOUR_project_id_PARAMETER";
var messageId = "YOUR_message_id_PARAMETER";
var region = "us";
var pathname = "/v1/projects/%7Bproject_id%7D/messages/%7Bmessage_id%7D";
var request = HttpRequest.newBuilder()
  .GET()
  .uri(URI.create(host + pathname ))
  .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(("<username>:<password>").getBytes()))
  .build();

var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
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.

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