{{announcement.body}}
{{announcement.title}}

Alexa Skill With Spring Boot

DZone 's Guide to

Alexa Skill With Spring Boot

This project will walk through how to build an Alexa Skill with Spring Boot and Http Servlet mapping examples.

· Java Zone ·
Free Resource

You can build a custom skill for Alexa by extending a servlet that accepts requests from and sends responses to the Alexa service in the cloud.

This project will walk through how to build an Alexa Skill with Spring Boot and Http Servlet mapping examples.

Servlet mapping can be achieved either by using ServletRegistrationBean in Spring Boot as well as using Spring annotations. In this example, we are going to use the ServletRegistrationBean class to register the Alexa Servlet as a Spring bean.

Prerequisites

Here you have the technologies used in this project

  1. Java 1.8
  2. Alexa Skill Kit 2.29.0
  3. Spring Boot 2.5.0.RELEASE
  4. Maven 3.6.1
  5. IntelliJ IDEA
  6. ngrok

Structure of the Project

Find below the structure of this project:

Shell
 




x
15


 
1
  ├────src
2
  │    └───main
3
  │        ├───java
4
  │        │   └───com
5
  │        │       └───xavidop
6
  │        │           └───alexa
7
  │        │               ├───configuration
8
  │        │               ├───handlers
9
  │        │               ├───properties
10
  │        │               └───servlet
11
  │        │
12
  │        └───resources
13
  │                application.properties
14
  │                log4j2.xml
15
  └── pom.xml



These are the main folders and files of this project:

  • Configuration: This folder has the WebConfig class which will register the Alexa Http Servlet.
  • Handlers: All the Alexa handlers. They will process all Alexa requests.
  • Properties: Here you can find the PropertiesUtils class that read Spring application.propeties file.
  • Servlet: The entry point of POST Requests is here. This is the AlexaServlet.
  • Resources: Alexa, Spring, and Log4j2 configurations.
  • Pom.xml: Dependencies of this project.

Maven Dependencies

These are the dependencies used in this example. You can find them in pom.xml file:

Spring Boot:

XML
 




x


1
  <parent>
2
        <groupId>org.springframework.boot</groupId>
3
        <artifactId>spring-boot-starter-parent</artifactId>
4
        <version>2.2.5.RELEASE</version>
5
  </parent>



Alexa Skill Kit:

XML
 




x


1
 <dependency>
2
      <groupId>com.amazon.alexa</groupId>
3
      <artifactId>ask-sdk</artifactId>
4
      <version>2.29.0</version>
5
 </dependency>



Spring Boot Starter Web: 

XML
 




x


1
<dependency>
2
      <groupId>org.springframework.boot</groupId>
3
      <artifactId>spring-boot-starter-web</artifactId>
4
</dependency>



Log4j2:

XML
 




x
10


1
<dependency>
2
      <groupId>org.apache.logging.log4j</groupId>
3
      <artifactId>log4j-api</artifactId>
4
      <version>2.13.1</version>
5
</dependency>
6
<dependency>
7
      <groupId>org.apache.logging.log4j</groupId>
8
      <artifactId>log4j-core</artifactId>
9
      <version>2.13.1</version>
10
</dependency>



Spring Boot Maven Build Plug-in:

XML
 




x


 
1
 <build>
2
        <plugins>
3
            <plugin>
4
                <groupId>org.springframework.boot</groupId>
5
                <artifactId>spring-boot-maven-plugin</artifactId>
6
            </plugin>
7
        </plugins>
8
  </build>



The Alexa HTTP Servlet

Thanks to Alexa HTTP Servlet Support that you can find in the Alexa official GitHub repository and its SkillServlet class we can register it with Spring Boot using ServletRegistrationBean as following.

The SkillServlet class registers the skill instance from the SkillBuilder object and provides a doPost method which is responsible for deserialization of the incoming request, verification of the input request before invoking the skill, and serialization of the generated response.

Our AlexaServlet class, located in the servlet folder extends SkillServlet and after it registers as a servlet, it will be our main entry point.

This is how this class looks like:

Java
 




x
20


 
1
public class AlexaServlet extends SkillServlet {
2
 
          
3
      public AlexaServlet() {
4
          super(getSkill());
5
      }
6
 
          
7
      private static Skill getSkill() {
8
          return Skills.standard()
9
                  .addRequestHandlers(
10
                          new CancelandStopIntentHandler(),
11
                          new HelloWorldIntentHandler(),
12
                          new HelpIntentHandler(),
13
                          new LaunchRequestHandler(),
14
                          new SessionEndedRequestHandler())
15
                  // Add your skill id below
16
                  //.withSkillId("")
17
                  .build();
18
      }
19
 
          
20
  }



It will receive all POST requests from Alexa and will send them to a specific handler, located in handlers folders, that can manage those requests.

Registering the Alexa HTTP Servlet as Spring Beans Using ServletRegistrationBean

We need to create a bean of this class in our Spring Configuration class. The most relevant methods of the ServletRegistrationBean class that we used in this project are:

  • setServlet: Sets the servlet to be registered. In our case, AlexaServlet.
  • addUrlMappings: Add URL mappings for the Servlet. We used /alexa.
  • setLoadOnStartup: Sets priority to load Servlet on startup. It is not as important as the two methods above because we only have one HTTP Servlet in this example.

The WebConfig class is where we register the Alexa Http Servlet. This is how we register the servlet:

Java
 




x
11


 
1
  @Bean
2
  public ServletRegistrationBean<HttpServlet> alexaServlet() {
3
 
          
4
      loadProperties();
5
 
          
6
      ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
7
      servRegBean.setServlet(new AlexaServlet());
8
      servRegBean.addUrlMappings("/alexa/*");
9
      servRegBean.setLoadOnStartup(1);
10
      return servRegBean;
11
  }



Setting Properties

The servlet must meet certain requirements to handle requests sent by Alexa and adhere to the Alexa Skills Kit interface standards. For more information, see Host a Custom Skill as a Web Service in the Alexa Skills Kit technical documentation.

In this example you have four properties that you can set in application.properties file:

  • Server.port: The port that the Spring Boot app will be used.
  • Com.amazon.ask.servlet.disableRequestSignatureCheck: Disable/enable security.
  • Com.amazon.speech.speechlet.servlet.timestampTolerance: The maximum gap between the timestamps of the request and the current local time of execution. In milliseconds.
  • Javax.net.ssl.keyStore: If the first property is set to false then you have to specify the path of your Keystore file.
  • Javax.net.ssl.keyStorePassword: If the first property is set to false then you have to specify the password of your Keystore.

Build the Skill With Spring Boot

As it is a maven project, you can build the Spring Boot application running this command:

mvn clean package

Run the Skill With Spring Boot

Run the AlexaSkillAppStarter.java class as Java application i.e. go to Run→ Run as → Java Application

Or, you can use:

mvn spring-boot:run

After executing the main class, you can send Alexa POST requests to http://localhost:8080/alexa.

Debug the Skill With Spring Boot

For debugging the Spring boot app as Java application i.e. go to Debug→ Debug as → Java Application.

Or, if you use IntelliJ IDEA, you can do a right-click in the Main method of AlexaSkillAppStarter class:

AlexaSkillAppStarter

After executing the main class in debug mode, you can send Alexa POST requests to http://localhost:8080/alexa and debug the Skill.

Test Requests Locally

I'm sure you already know the famous tool call Postman. REST APIs have become the new standard in providing a public and secure interface for your service. Though REST has become ubiquitous, it's not always easy to test. Postman makes it easier to test and manage HTTP REST APIs. Postman gives us multiple features to import, test and share APIs, which will help you and your team be more productive in the long run.

After running your application you will have an endpoint available at http://localhost:8080/alexa. With Postman you can emulate any Alexa Request.

For example, you can test a LaunchRequest

JSON
 




x
38


1
  {
2
    "version": "1.0",
3
    "session": {
4
      "new": true,
5
      "sessionId": "amzn1.echo-api.session.[unique-value-here]",
6
      "application": {
7
        "applicationId": "amzn1.ask.skill.[unique-value-here]"
8
      },
9
      "user": {
10
        "userId": "amzn1.ask.account.[unique-value-here]"
11
      },
12
      "attributes": {}
13
    },
14
    "context": {
15
      "AudioPlayer": {
16
        "playerActivity": "IDLE"
17
      },
18
      "System": {
19
        "application": {
20
          "applicationId": "amzn1.ask.skill.[unique-value-here]"
21
        },
22
        "user": {
23
          "userId": "amzn1.ask.account.[unique-value-here]"
24
        },
25
        "device": {
26
          "supportedInterfaces": {
27
            "AudioPlayer": {}
28
          }
29
        }
30
      }
31
    },
32
    "request": {
33
      "type": "LaunchRequest",
34
      "requestId": "amzn1.echo-api.request.[unique-value-here]",
35
      "timestamp": "2020-03-22T17:24:44Z",
36
      "locale": "en-US"
37
    }
38
  }



Pay attention with the timestamp field of the request to accomplish with the property com.amazon.speech.speechlet.servlet.timestampTolerance.

Test Requests Directly From Alexa

ngrok is a very cool, lightweight tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site or APIs.

When ngrok is running, it listens on the same port that you’re local web server is running on and proxies external requests to your local machine

From there, it’s a simple step to get it to listen to your web server. Say you’re running your local web server on port 8080. In the terminal, you’d type in: ngrok http 8080. This starts ngrok listening on port 8080 and creates the secure tunnel:

ngrok

So now you have to go to Alexa Developer Console, go to your skill > endpoints > https, add the https URL generated above followed by /Alexa. Eg: https://fe8ee91c.ngrok.io/alexa.

Select the My development endpoint is a sub-domain.... option from the dropdown and click save endpoint at the top of the page.

Go to the Test tab in the Alexa Developer Console and launch your skill.

The Alexa Developer Console will send an HTTPS request to the ngrok endpoint (https://fe8ee91c.ngrok.io/alexa) which will route it to your skill running on Spring Boot server at http://localhost:8080/alexa.

Conclusion

This example can be useful for all those developers who do not want to host their code in the cloud or do not want to use AWS Lambda functions. This is not a problem since, as you have seen in this example, Alexa gives you the possibility to create skills in different ways. I hope this example project is useful to you.

You can find the code in my Github.

That's all folks!

Happy coding!

Topics:
alexa, alexa skill, alexa skill development, alexa skills, alexa skills developer, alexa skills development, java, spring, spring boot

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}