Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

eBook – Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

1. Overview

WhatsApp Messenger is the leading messaging platform in the world, making it an essential tool for businesses to connect with their users.

By communicating over WhatsApp, we can enhance customer engagement, provide efficient support, and build stronger relationships with our users.

In this tutorial, we’ll explore how to send WhatsApp messages using Twilio within a Spring Boot application. We’ll walk through the necessary configuration, and implement functionality to send messages and handle user replies.

2. Setting up Twilio

To follow this tutorial, we’ll first need a Twilio account and a WhatsApp Business Account (WABA).

We’ll need to connect both of these accounts together by creating a WhatsApp Sender. Twilio offers a detailed setup tutorial that can be referenced to guide us through this process.

Once we set up our WhatsApp Sender successfully, we can proceed with sending messages to and receiving messages from our users.

3. Setting up the Project

Before we can use Twilio to send WhatsApp messages, we’ll need to include an SDK dependency and configure our application correctly.

3.1. Dependencies

Let’s start by adding the Twilio SDK dependency to our project’s pom.xml file:

<dependency>
    <groupId>com.twilio.sdk</groupId>
    <artifactId>twilio</artifactId>
    <version>10.4.1</version>
</dependency>

3.2. Defining Twilio Configuration Properties

Now, to interact with the Twilio service and send WhatsApp messages to our users, we need to configure our account SID and auth token to authenticate API requests. We’ll also need the messaging service SID to specify which messaging service, using our WhatsApp-enabled Twilio phone number, we want to use for sending the messages.

We’ll store these properties in our project’s application.yaml file and use @ConfigurationProperties to map the values to a POJO, which our service layer references when interacting with Twilio:

@Validated
@ConfigurationProperties(prefix = "com.baeldung.twilio")
class TwilioConfigurationProperties {

    @NotBlank
    @Pattern(regexp = "^AC[0-9a-fA-F]{32}$")
    private String accountSid;

    @NotBlank
    private String authToken;

    @NotBlank
    @Pattern(regexp = "^MG[0-9a-fA-F]{32}$")
    private String messagingSid;

    // standard setters and getters

}

We’ve also added validation annotations to ensure all the required properties are configured correctly. If any of the defined validations fail, it results in the Spring ApplicationContext failing to start up. This allows us to conform to the fail fast principle.

Below is a snippet of our application.yaml file, which defines the required properties that’ll be mapped to our TwilioConfigurationProperties class automatically:

com:
  baeldung:
    twilio:
      account-sid: ${TWILIO_ACCOUNT_SID}
      auth-token: ${TWILIO_AUTH_TOKEN}
      messaging-sid: ${TWILIO_MESSAGING_SID}

Accordingly, this setup allows us to externalize the Twilio properties and easily access them in our application.

3.3. Initializing Twilio at Startup

To invoke the methods exposed by the SDK successfully, we need to initialize it once at startup. To achieve this, we’ll create a TwilioInitializer class that implements the ApplicationRunner interface:

@Component
@EnableConfigurationProperties(TwilioConfigurationProperties.class)
class TwilioInitializer implements ApplicationRunner {

    private final TwilioConfigurationProperties twilioConfigurationProperties;

    // standard constructor

    @Override
    public void run(ApplicationArguments args) {
        String accountSid = twilioConfigurationProperties.getAccountSid();
        String authToken = twilioConfigurationProperties.getAuthToken();
        Twilio.init(accountSid, authToken);
    }

}

Using constructor injection, we inject an instance of our TwilioConfigurationProperties class we created earlier. Then we use the configured account SID and auth token to initialize the Twilio SDK in the run() method.

This ensures that Twilio is ready to use when our application starts up. This approach is better than initializing the Twilio client in our service layer each time we need to send a message.

4. Sending WhatsApp Messages

Now that we’ve defined our properties, let’s create a WhatsAppMessageDispatcher class and reference them to interact with Twilio.

For this demonstration, we’ll take an example where we want to notify our users whenever we publish a new article on our website. We’ll send them a WhatsApp message with a link to the article, so they can easily check it out.

4.1. Configuring Content SID

To restrict businesses from sending unsolicited or spammy messages, WhatsApp requires that all business-initiated notifications be templated and pre-registered. These templates are identified by a unique content SID, which must be approved by WhatsApp before we can use it in our application.

For our example, we’ll configure the following message template:

New Article Published. Check it out : {{ArticleURL}}

Here, {{ArticleURL}} is a placeholder that’ll be replaced with the actual URL of the newly published article when we send out the notification.

Now, let’s define a new nested class inside our TwilioConfigurationProperties class to hold our content SID:

@Valid
private NewArticleNotification newArticleNotification = new NewArticleNotification();

class NewArticleNotification {

    @NotBlank
    @Pattern(regexp = "^HX[0-9a-fA-F]{32}$")
    private String contentSid;

    // standard setter and getter

}

We again add validation annotations to ensure that we configure the content SID correctly and it matches the expected format.

Similarly, let’s add the corresponding content SID property to our application.yaml file:

com:
  baeldung:
    twilio:
      new-article-notification:
        content-sid: ${NEW_ARTICLE_NOTIFICATION_CONTENT_SID}

4.2. Implementing the Message Dispatcher

Now that we’ve configured our content SID, let’s implement the service method to send out notifications to our users:

public void dispatchNewArticleNotification(String phoneNumber, String articleUrl) {
    String messagingSid = twilioConfigurationProperties.getMessagingSid();
    String contentSid = twilioConfigurationProperties.getNewArticleNotification().getContentSid();
    PhoneNumber toPhoneNumber = new PhoneNumber(String.format("whatsapp:%s", phoneNumber));

    JSONObject contentVariables = new JSONObject();
    contentVariables.put("ArticleURL", articleUrl);

    Message.creator(toPhoneNumber, messagingSid)
      .setContentSid(contentSid)
      .setContentVariables(contentVariables.toString())
      .create();
}

In our dispatchNewArticleNotification() method, we’re using the configured messaging SID and content SID to send out a notification to the specified phone number. We’re also passing the article URL as a content variable, which will be used to replace the placeholder in our message template.

It’s important to note that we can also configure a static message template without any placeholders. In such case, we can simply omit the call to the setContentVariables() method.

5. Handling WhatsApp Replies

Once we’ve sent out our notifications, our users might reply with their thoughts or questions. When a user replies to our WhatsApp business account, a 24-hour session window is initiated during which we can communicate with our users using free-form messages, without the need for pre-approved templates.

To automatically handle user replies from our application, we need to configure a webhook endpoint in our Twilio messaging service. The Twilio service calls this endpoint whenever a user sends a message. We receive multiple parameters in the configured API endpoint that we can use to customize our response.

Let’s see how we can create such an API endpoint in our Spring Boot application.

5.1. Implementing the Reply Message Dispatcher

First, we’ll create a new service method in our WhatsAppMessageDispatcher class to dispatch a free-form reply message:

public void dispatchReplyMessage(String phoneNumber, String username) {
    String messagingSid = twilioConfigurationProperties.getMessagingSid();
    PhoneNumber toPhoneNumber = new PhoneNumber(String.format("whatsapp:%s", phoneNumber));

    String message = String.format("Hey %s, our team will get back to you shortly.", username);
    Message.creator(toPhoneNumber, messagingSid, message).create();
}

In our dispatchReplyMessage() method, we send a personalized message to the user, addressing them by their username and letting them know that our team will get back to them shortly.

It’s worth noting that we can even send multimedia messages to our users during the 24-hour session.

5.2. Exposing the Webhook Endpoint

Next, we’ll expose a POST API endpoint in our application. The path of this endpoint should match the webhook URL we’ve configured in our Twilio messaging service:

@PostMapping(value = "/api/v1/whatsapp-message-reply")
public ResponseEntity<Void> reply(@RequestParam("ProfileName") String username,
        @RequestParam("WaId") String phoneNumber) {
    whatsappMessageDispatcher.dispatchReplyMessage(phoneNumber, username);
    return ResponseEntity.ok().build();
}

In our controller method, we accept the ProfileName and WaId parameters from Twilio. These parameters contain the username and phone number of the user who sent the message, respectively. We then pass these values to our dispatchReplyMessage() method to send a response back to the user.

We’ve used the ProfileName and WaId parameters for our example. But as mentioned previously, Twilio sends multiple parameters to our configured API endpoint. For example, we can access the Body parameter to retrieve the text content of the user’s message. We could potentially store this message in a queue and route it to the appropriate support team for further processing.

6. Testing the Twilio Integration

Now that we’ve implemented the functionality to send WhatsApp messages using Twilio, let’s look at how we can test this integration.

Testing external services can be challenging, as we don’t want to make actual API calls to Twilio during our tests. This is where we’ll use MockServer, which will allow us to simulate the outgoing Twilio calls.

6.1. Configuring the Twilio REST Client

In order to route our Twilio API requests to MockServer, we need to configure a custom HTTP client for the Twilio SDK.

We’ll create a class in our test suite that creates an instance of TwilioRestClient with a custom HttpClient:

class TwilioProxyClient {

    private final String accountSid;
    private final String authToken;
    private final String host;
    private final int port;

    // standard constructor

    public TwilioRestClient createHttpClient() {
        SSLContext sslContext = SSLContextBuilder.create()
          .loadTrustMaterial((chain, authType) -> true)
          .build();
        
        HttpClientBuilder clientBuilder = HttpClientBuilder.create()
          .setSSLContext(sslContext)
          .setProxy(new HttpHost(host, port));

        HttpClient httpClient = new NetworkHttpClient(clientBuilder);
        return new Builder(accountSid, authToken)
          .httpClient(httpClient)
          .build();
    }

}

In our TwilioProxyClient class, we create a custom HttpClient that routes all requests through a proxy server specified by the host and port parameters. We also configure the SSL context to trust all certificates, as MockServer uses a self-signed certificate by default.

6.2. Configuring the Test Environment

Before we write our test, we’ll create an application-integration-test.yaml file in our src/test/resources directory with the following content:

com:
  baeldung:
    twilio:
      account-sid: AC123abc123abc123abc123abc123abc12
      auth-token: test-auth-token
      messaging-sid: MG123abc123abc123abc123abc123abc12
      new-article-notification:
        content-sid: HX123abc123abc123abc123abc123abc12

These dummy values bypass the validation we’d configured earlier in our TwilioConfigurationProperties class.

Now, let’s set up our test environment using the @BeforeEach annotation

@Autowired
private TwilioConfigurationProperties twilioConfigurationProperties;

private MockServerClient mockServerClient;

private String twilioApiPath;

@BeforeEach
void setUp() {
    String accountSid = twilioConfigurationProperties.getAccountSid();
    String authToken = twilioConfigurationProperties.getAuthToken();

    InetSocketAddress remoteAddress = mockServerClient.remoteAddress();
    String host = remoteAddress.getHostName();
    int port = remoteAddress.getPort();

    TwilioProxyClient twilioProxyClient = new TwilioProxyClient(accountSid, authToken, host, port);
    Twilio.setRestClient(twilioProxyClient.createHttpClient());
    
    twilioApiPath = String.format("/2010-04-01/Accounts/%s/Messages.json", accountSid);
}

In our setUp() method, we create an instance of our TwilioProxyClient class, passing in the host and port of the running MockServer instance. This client is then used to set a custom RestClient for the Twilio SDK. We also store the API path for sending messages in the twilioApiPath variable.

6.3. Validating the Twilio Request

Finally, let’s write a test case to verify that our dispatchNewArticleNotification() method sends the expected request to Twilio:

// Set up test data
String contentSid = twilioConfigurationProperties.getNewArticleNotification().getContentSid();
String messagingSid = twilioConfigurationProperties.getMessagingSid();
String contactNumber = "+911001001000";
String articleUrl = RandomString.make();

// Configure mock server expectations
mockServerClient
  .when(request()
    .withMethod("POST")
    .withPath(twilioApiPath)
    .withBody(new ParameterBody(
        param("To", String.format("whatsapp:%s", contactNumber)),
        param("ContentSid", contentSid),
        param("ContentVariables", String.format("{\"ArticleURL\":\"%s\"}", articleUrl)),
        param("MessagingServiceSid", messagingSid)
    ))
  )
  .respond(response()
    .withStatusCode(200)
    .withBody(EMPTY_JSON));

// Invoke method under test
whatsAppMessageDispatcher.dispatchNewArticleNotification(contactNumber, articleUrl);

// Verify the expected request was made
mockServerClient.verify(request()
  .withMethod("POST")
  .withPath(twilioApiPath)
  .withBody(new ParameterBody(
      param("To", String.format("whatsapp:%s", contactNumber)),
      param("ContentSid", contentSid),
      param("ContentVariables", String.format("{\"ArticleURL\":\"%s\"}", articleUrl)),
      param("MessagingServiceSid", messagingSid)
  )),
    VerificationTimes.once()
);

In our test method, we first set up the test data and configure MockServer to expect a POST request to the Twilio API path with specific parameters in the request body. We also instruct MockServer to respond with a 200 status code and an empty JSON body when this request is made.

Next, we invoke our dispatchNewArticleNotification() method with the test data and verify that the expected request was made to MockServer exactly once.

By using MockServer to simulate the Twilio API, we ensure that our integration works as expected without actually sending any messages or incurring any costs.

7. Conclusion

In this article, we explored how to send WhatsApp messages using Twilio from a Spring Boot application.

We walked through the necessary configurations and implemented the functionality to send templated notifications to our users with dynamic placeholders.

Finally, we handled user replies to our notifications by exposing a webhook endpoint to receive the reply data from Twilio and created a service method to dispatch a generic non-templated reply message.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
eBook – eBook Guide Spring Cloud – NPI (cat=Cloud/Spring Cloud)