Spring Boot - Make a Voice Call Using Twilio
In this blog, we will use the Twilio API to make a voice call using our Spring Boot application.
Create a Spring Boot Application
- Go to https://start.spring.io/
We will go for a maven project for this article.
Generate the project and a zip file will download.
Unzip the project and open the project in any IDE of your preference ( IntelliJ, VSCode, Eclipse )
Add Twilio Dependency to the pom.xml file
Go to https://www.twilio.com/docs/libraries/java
OR
Copy the following dependency
pom.xml
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>9.2.1</version>
</dependency>
Create a Twilio Account
After signing up you will get an
Account SID
Auth Token
Twilio Phone Number
Create a Configuration file for Twilio
- Add a Config.java files
Config.java
import com.twilio.Twilio;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Config
{
public final static String VC_ACCOUNT_SID = "Your Twilio SID";
public final static String VC_AUTH_ID = "Your Twilio Auth Token";
public final static String VC_FROM_NUMBER ="Your Twilio Phone Number";
public final static String VC_TO_NUMBER =
"The number you want to make a call to";
static {
Twilio.init(VC_ACCOUNT_SID, VC_AUTH_ID);
}
}
Note 1:
Make sure you add the country code in VC_TO_NUMBER. For example, if the country code is +91, then VC_TO_NUMBER should be "+91XXXXXXXXXX"
Note 2:
Make sure you add the "@ Configuration" annotation
Implement ApplicationRunner interface
We will implement
ApplicationRunner
interface so that the call is made as soon as we run the application.Add a MyAppRunner.java class
MyAppRunner.java
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.type.PhoneNumber;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.net.URI;
@Component
public class MyAppRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
Call.creator(
new PhoneNumber(Config.VC_TO_NUMBER),
new PhoneNumber(Config.VC_FROM_NUMBER),
new URI("http://demo.twilio.com/docs/voice.xml")).create();
}
}
Run the application
- Now run the application and if there are no errors, then you will see a voice call on the mobile number you used in the code.
I hope you found the article useful.
Let's connect :
Happy Coding :)