Sending SMS from Twilio
1. Entity – TwilioRequest
Java
import lombok.AllArgsConstructor; import lombok.Data; @Data public class TwilioRequest { private final String toPhoneNumber; private final String fromPhoneNumber; private final String message; } |
This is our Entity – TwilioRequest, It contains – message, the Twilio Number (sender) and the cell phone number (receiver)
2. RestController for Sending SMS
Java
import com.w3wiki.Twilio.Entity.TwilioRequest; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping ( "/sms" ) public class SmsController { @PostMapping ( "/send" ) public ResponseEntity<String> sendMessage( @RequestBody TwilioRequest twilioRequest) { // Check if RequestBody has valid data or NOT if (twilioRequest == null || twilioRequest.getFromPhoneNumber() == null || twilioRequest.getToPhoneNumber() == null || twilioRequest.getMessage() == null ) { return ResponseEntity.badRequest().body( "Invalid request data" ); } // Extract Request Data String fromNumber = twilioRequest.getFromPhoneNumber(); String toNumber = twilioRequest.getToPhoneNumber(); String msg = twilioRequest.getMessage(); // Create Message to be sent Message.creator( new PhoneNumber(toNumber), new PhoneNumber(fromNumber), msg).create(); return ResponseEntity.ok( "SMS sent Succesfully !" ); } } |
Explanation of above Program:
- URL endpoint to send SMS: /sms/send. And we’ve used REST – POST Mapping to send SMS.
- Firstly, we check if the data received in Request Body is valid or not. If its not, we won’t proceed further and return error – ‘Bad Request’, Status : 400.
- If the request body is validated, we then extract the data into our entity (TwilioRequest), then create a Message using .creator() method which takes 3 parameters – To_Number(Receiver) , From_Number – Its the twilio number (sender) and the message.
3. RestController for Making Voice Calls
Java
import com.w3wiki.Twilio.Entity.TwilioRequest; import com.twilio.rest.api.v2010.account.Call; import com.twilio.type.PhoneNumber; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; @RestController @RequestMapping ( "/call" ) public class VoiceCallController { @PostMapping ( "/voiceCall" ) public ResponseEntity<String> makeVoiceCall( @RequestBody TwilioRequest twilioRequest) throws Exception { // Check if RequestBody has valid data or NOT // In this example, the message field doesn't have to be checked if (twilioRequest == null || twilioRequest.getFromPhoneNumber() == null || twilioRequest.getToPhoneNumber() == null ) { return ResponseEntity.badRequest().body( "Invalid request data" ); } // Extract Request Data String fromNumber = twilioRequest.getFromPhoneNumber(); String toNumber = twilioRequest.getToPhoneNumber(); // Make a call Call.creator( new PhoneNumber(fromNumber), new PhoneNumber(toNumber), new URI( "http://demo.twilio.com/docs/voice.xml" )).create(); return ResponseEntity.ok( "Call made Succesfully !" ); } } |
Explanation of above Program:
- URL Endpoint exposed to make the call: /call/voiceCall, POST Mapping used.
- Just like the SMSController, we perform validation here. However, in this case we don’t really need a message. As this is going to be a sample voice call. Same validation is going to be checked, if the request body has valid data.
- We call the creator() method of class – Call. And it also takes the parameters as the sender and receiver in which sender is the Twilio Number, & receiver is the cell phone number of a user.
- URI – Uniform Resource Identifier is used to locate and access the resource. We’ve provided the sample voice message URI for testing purpose.
Note: Messages and voice calls can only be made to the number verified with twilio account if you have a trial account.
4. Spring Boot Application
Java
import com.twilio.Twilio; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TwilioApplication{ // Twilio Credentials private final static String ACCOUNT_SID = "<Your_TWILIO_ACCOUNT_SID>" ; private final static String AUTH_ID = "<Your_TWILIO_AUTH_ID>" ; // Initializing the Twilio // Java Library with our credentials static { Twilio.init(ACCOUNT_SID, AUTH_ID); } // Start Spring Application public static void main(String[] args) {SpringApplication.run(TwilioApplication. class , args);} } |
Explanation of the above Program:
- This is our Twilio Spring Boot Application code that contains the credentials to associate it with our account and perform all the REST Functionalities.
- Now we can run this application and test our code on POSTMAN.
Postman SMS Controller Output:
Output Message Received on Cell:
PostMan VoiceController Output:
Once this is executed, you’ll receive a demo call from Twilio.
Spring Boot – Sending SMS with Twilio
Spring is a widely used framework of Java that allows us to create stand-alone and robust applications at the enterprise level. Spring boot is a tool or an extension of the Spring framework that makes developing web applications and microservices much faster and easier. It offers an integrated server & its auto-configuration feature makes it a top-notch tool for software development.
Twilio is a cloud communication platform that provides programmable communication tools – APIs for adding message, voice and video communication to your application. In this article, we’ll learn how to integrate Twilio API functionality using Spring Boot.
Pre-requisites of Topic
- Java JDK version 8 or newer
- Twilio Account: Free or Paid Twilio account, Twilio ACCOUNT_SID, Twilio AUTH_ID.
- REST Controllers, Response entity, Post Man, Build Tool: Maven