twilio-java SDK

repository·main·Indexed 19 days ago

https://github.com/twilio/twilio-java

The official Java SDK for interacting with the Twilio REST API, allowing developers to programmatically manage communications such as SMS and voice. It supports Java 8, 11, 17, and 21, and provides tools for TwiML generation, automatic pagination, and custom TwilioRestClient configurations for proxy servers or custom HTTP headers.

Tokens
8.6K
Snippets
25
Records
40
Agent score
67%

What's inside twilio-java

  1. How TwilioRestClient and HttpClient work together

    main

    The TwilioRestClient is the high-level object used to make API requests. It relies on an abstraction called com.twilio.http.HttpClient to perform the actual network operations.

    • TwilioRestClient: Manages credentials and orchestrates requests.
    • com.twilio.http.HttpClient: An interface that allows you to plug in any HTTP implementation.
    • NetworkHttpClient: The library's default implementation of com.twilio.http.HttpClient. It wraps an Apache HttpClient (specifically org.apache.http.client.HttpClient) to bridge the gap between the Twilio library and the Apache HTTP components.
  2. Understand the @Beta annotation

    main

    The Twilio Java SDK uses the @Beta annotation to mark classes or methods that are in beta. Elements marked with @Beta are subject to change in future releases.

    @Beta
    public class ClassName {
      // Class implementation
    }
    
    public class ClassName {
      @Beta
      public void init() {
        // Implementation
      }
    }
  3. Identify supported versions of twilio-java

    main
    Twilio only provides support for the current MAJOR version of the twilio-java library. All new features, functionality, bug fixes, and security updates are exclusively applied to the current major version. If you are using an older major version, you will not receive updates or security patches.
  4. Iterate through records with automatic paging

    main

    The library handles pagination automatically when using the read method. You can specify a limit (total records to receive) and a pageSize (maximum size per page fetch). As you iterate over the resulting ResourceSet, the library fetches new pages under the hood.

    import com.twilio.Twilio;
    import com.twilio.base.ResourceSet;
    import com.twilio.rest.api.v2010.account.Call;
    
    public class Example {
      public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
      public static final String AUTH_TOKEN = "your_auth_token";
    
      public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
    
        ResourceSet<Call> calls = Call.reader().read();
    
        for (Call call : calls) {
          System.out.println(call.getDirection());
        }
      }
    }
  5. Understand the twilio-java versioning strategy

    main

    The twilio-java library follows a modified Semantic Versioning (MAJOR.MINOR.PATCH) system. To ensure stability, it is strongly recommended to pin at least the major version (and ideally the minor version) in your dependency management tool to prevent unexpected breaking changes.

    Version Increments

    • PATCH (MAJOR.MINOR.PATCH): Incremented for backwards-compatible bug fixes. These are generally safe to upgrade.
    • MINOR (MAJOR.MINOR.PATCH): Incremented when new features are added in a backwards-compatible way or when small, limited breaking changes (such as function signature changes) are introduced. Upgrading may require manual code adjustments.
    • MAJOR (MAJOR.MINOR.PATCH): Incremented for significant breaking changes that require extensive code reworking. New major versions are communicated in advance via Release Candidates and a schedule.
  6. Install the Twilio Java SDK

    main

    The Twilio Java SDK can be installed using Maven or Gradle. For manual compilation, you can clone the repository and use Maven to build the project locally.

    Maven

    Add the following dependency to your pom.xml:

    Gradle

    Add the following dependency to your build.gradle:

    Manual Compilation

    If you wish to compile the library from source, clone the repository and run mvn install.

    <!-- Maven -->
    <dependency>
      <groupId>com.twilio.sdk</groupId>
      <artifactId>twilio</artifactId>
      <version>12.X.X</version>
      <scope>compile</scope>
    </dependency>
    
    <!-- Gradle -->
    implementation "com.twilio.sdk:twilio:12.X.X"
    
    <!-- Manual Build -->
    git clone git@github.com:twilio/twilio-java
    cd twilio-java
    mvn install
  7. Migrate from 11.x.x to 12.x.x: Replace SignatureAlgorithm with SecureDigestAlgorithm

    main

    In version 12.0.0, the deprecated io.jsonwebtoken.SignatureAlgorithm enum is replaced by the io.jsonwebtoken.security.SecureDigestAlgorithm API from jjwt 0.12.x.

    Impacted Users: Users who pass an explicit algorithm parameter to ValidationClient, ValidationInterceptor, ValidationToken.fromHttpRequest(), ValidationToken.Builder.algorithm(), or who subclass com.twilio.jwt.Jwt directly.

    Not Impacted: Users using default constructors for ValidationClient or ValidationInterceptor, or those only using AccessToken, ClientCapability, TaskRouterCapability, or REST API resource classes (e.g., Message, Call).

    // 11.x.x
    import io.jsonwebtoken.SignatureAlgorithm;
    
    new ValidationClient(accountSid, credSid, signingKeySid, privateKey, SignatureAlgorithm.PS256);
    
    new ValidationToken.Builder(accountSid, credSid, signingKeySid, privateKey)
        .algorithm(SignatureAlgorithm.RS256)
        .build();
    // 12.x.x
    import io.jsonwebtoken.Jwts;
    
    new ValidationClient(accountSid, credSid, signingKeySid, privateKey, Jwts.SIG.PS256);
    
    new ValidationToken.Builder(accountSid, credSid, signingKeySid, privateKey)
        .algorithm(Jwts.SIG.RS256)
        .build();
  8. Use a custom TwilioRestClient to modify HTTP requests

    main

    By default, the Twilio Java helper library creates a default TwilioRestClient using the credentials provided in Twilio.init(ACCOUNT_SID, AUTH_TOKEN). However, you can provide your own TwilioRestClient instance to override the default behavior. This is useful for connecting through a proxy server, adding custom HTTP headers, or implementing a mocking layer for unit testing.

    To use a custom client, instantiate your TwilioRestClient and pass it to Twilio.setRestClient(twilioRestClient). All subsequent Twilio REST API calls will use this custom client.

    // 1. Initialize Twilio with credentials
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
    
    // 2. Create your custom TwilioRestClient
    TwilioRestClient twilioRestClient = myCustomClientCreator.getClient();
    
    // 3. Inject the custom client into the Twilio library
    Twilio.setRestClient(twilioRestClient);
    
    // 4. Now, API calls will use your custom client
    Message message = Message.creator(
        new PhoneNumber("+15558675310"),
        new PhoneNumber("+15017122661"),
        "Hey there!"
    ).create();
  9. Initialize the Twilio Client

    main

    To use the Twilio Java library, you must first initialize the client with your ACCOUNT_SID and AUTH_TOKEN. This is typically done using Twilio.init(accountSid, authToken).

    If you are accessing endpoints that do not require basic authentication, use the TwilioNoAuth client. For endpoints requiring bearer tokens (like the Organization domain), you must use a custom client initialized with the necessary values for access token generation. Alternatively, you can implement the Token interface to provide a custom token manager implementation to bypass manual initialization steps.

    import com.twilio.Twilio;
    import com.twilio.exception.AuthenticationException;
    
    public class Example {
    
      private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
      private static final String AUTH_TOKEN = "your_auth_token";
    
      public static void main(String[] args) throws AuthenticationException {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
      }
    }
  10. Migrate from 7.x.x to 7.17.x: TwiML Package Reorganization

    main

    In version 7.17.x, the TwiML module was reorganized into sub-packages based on context (e.g., voice, messaging, fax) to improve scalability.

    Example Package Changes:

    • com.twilio.twiml.Message $\rightarrow$ com.twilio.twiml.messaging.Message
    • com.twilio.twiml.Dial $\rightarrow$ com.twilio.twiml.voice.Dial
    • com.twilio.twiml.Say $\rightarrow$ com.twilio.twiml.voice.Say
  11. Migrate from 7.x.x to 8.x.x: Replace Guava with Java Concurrency

    main

    Version 8.0.0 dropped support for Java 7 and removed several Guava dependencies in favor of built-in Java 8+ functionality.

    Executor Service Migration: Replace com.google.common.util.concurrent.ListeningExecutorService with java.util.concurrent.ExecutorService.

    Asynchronous Request Migration: All asynchronous createAsync, fetchAsync, etc., return types changed from Guava's ListenableFuture to java.util.concurrent.CompletableFuture.

    // 7.x.x
    import com.google.common.util.concurrent.ListeningExecutorService;
    import com.google.common.util.concurrent.MoreExecutors;
    
    ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    Twilio.setExecutorService(listeningExecutorService);
    
    // Async return type
    ListenableFuture<IncomingPhoneNumber> incomingPhoneNumber = IncomingPhoneNumber.creator(new PhoneNumber("+11234567890")).createAsync();
    // 8.x.x
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executor;
    
    ExecutorService executorService = Executors.newCachedThreadPool();
    Twilio.setExecutorService(executorService);
    
    // Async return type
    CompletableFuture<IncomingPhoneNumber> incomingPhoneNumber = IncomingPhoneNumber.creator(new PhoneNumber("+11234567890")).createAsync();