Three Tips for Coding With The Alexa SMAPI SDK

Greg Bulmash May 15, 2020
Share:
SMAPI Tips & Tools API
Blog_Header_Post_Img

The SMAPI SDK makes it easier than ever to build Alexa skill management and reporting functions into web, mobile, and desktop apps using one of the supported languages (Node.js, Python, and Java).

The Alexa Skill Management API (SMAPI) provides a REST-based API to do anything with your skills that you can do with the Alexa Skills Kit Command Line Interface (ASK CLI) or the Alexa developer console. In fact, a lot of the functionality of both utilize it. Recently, Amazon released the Alexa SMAPI SDK to make incorporating the Skill Management API into your code easier. This blog post offers some tips for working with the SDK, by walking through the NodeJS example scripts in the Alexa Cookbook SMAPI SDK demo.

Setup

If you want to build along with this post, download the demo from the Alexa Cookbook on Github.

The README.md (which you can read on Github or in the directory you downloade it into) gives you the important details on getting the examples set up, such as getting your credentials and vendor ID.

Setup tip: When you set up or choose a Login with Amazon security profile, go into the "Web Settings" for the profile and add "http://127.0.0.1:9090/cb" to the "Allowed Return URLs" so the ASK CLI can receive your SMAPI SDK credentials. This tip is specific to using the demo, because the tokens are being sent back to the CLI running on your computer, but it leads to a tip about getting tokens for your customers.

Tip #1: Integrate Login with Amazon Into Your Code

If you’re writing this code to work with multiple Amazon developer accounts and you can’t run the CLI with every customer, use your security profile and the Alexa scopes with a Login with Amazon integration in your app to get the tokens you need to access the API on behalf of your customers.

Running the listSkills.js Sample

The cookbook sample scripts follow the basic process to create and use a SMAPI client, described in the “Getting Started” directions of the SMAPI SDK for node.js

  1. Import the SDK.
  2. Import the credentials object that’s separated out into “tokens.js” to make it easy to use the credentials across both scripts.
  3. Import the Node “util” package. 
  4. Create the “refreshTokenConfig“ object.
  5. Create the SMAPI client.

Copied to clipboard
// Import the sdk
const Alexa = require('ask-smapi-sdk');
// Import your authentication info
const Token = require('./tokens.js');
// And the util library will make for more readable output
const util = require('util');
// specify the refreshTokenConfig with clientId and clientSecret 
// from your Login with Amazon client config 
// and access/refresh tokens generated via the ASK CLI
const refreshTokenConfig = {
  "clientId": Token.client_Id,
  "clientSecret": Token.client_Secret, 
  "refreshToken": Token.refresh_token,
  "accessToken": Token.access_token
}

//build the SMAPI client
const smapiClient = new Alexa.StandardSmapiClientBuilder()
    .withRefreshTokenConfig(refreshTokenConfig)
    .client();

This is the start of both the demo scripts. With correct credentials, the "listskills.js" script will run with no further editing. If you've got everything set up, it runs and lists the skills belonging to the account you used to login and get your credentials.

Copied to clipboard
// This retrieves a list of the skills associated with
// your vendorId. You can use that info for other demos.
smapiClient.listSkillsForVendorV1(Token.vendorId)
    .then((response) => {
        console.log(util.inspect(response, {"showHidden":false, "depth":4, "colors": true, "compact": false}));
    })
    .catch((err) => {
        console.log(err.message);
        console.log(util.inspect(err, {"showHidden":false, "depth":4, "colors": true, "compact": false}));;
    });

Tip #2: You Don’t Need to Know the Vendor ID in Advance

These scripts are simplified for the sake of a quick and easy demo. Rather than manually get your Vendor ID from the Alexa Developer Console and add it to the code, smapiClient.getVendorListV1() will return an array of vendors associated with the account, complete with Vendor IDs, names, and roles. You can choose one from there.

Running the getMetrics.js Sample

Now open the "getMetrics.js" script. It's useful to break down the SDK operation to get your metrics, because there are a number of things going on here.

Here's the main function call:

Copied to clipboard
smapiClient.getSkillMetricsV1(
  '[skill ID]',
  '[start date/time]',
  '[end date/time]',
  '[Period]',
  '[metric]',
  '[stage]',
  '[type]'
)

It may not be immediately obvious where the "GetSkillMetricsV1" method comes from, because it's not in the Metrics API documentation. That particular string is a combination of the corresponding "operation name" and the API version, which can be found in the "Operation names and supported versions" table of the Audit Logs documentation.

Tip 3: Use Your Editor's Autocomplete Suggestions to Search the Available Methods

Probably the easiest way to find the SDK version of the SMAPI function you want to use is with the auto-complete suggestions in your editor (if it offers that). Here’s an example of how it works in Visual Studio Code:

VS Code narrowing down methods

After you've defined the "smapiClient" variable in your code, typing "smapiClient." (note the period at the end of the string) brings up a list of potential methods and properties that follow. As you type letters after the period, the list gets refined, so 'smapiClient.metrics" shows you two options: "getSkillMetricsV1" and "callGetSkillMetricsV1."  

They're essentially the same method, except the one with "call" at the beginning returns more information about the HTTP exchange with the API, while the one without just returns the results.

Select one and type an opening parenthesis. You'll get a list of the arguments.

VS Code showing method arguments. Text representation follows.
Copied to clipboard
getSkillMetricsV1(skillId: string, startTime: string, endTime: string, period: string, metric: string, stage: string, skillType: string, intent?: string, locale?: string, maxResults?: number, nextToken?: string): Promise<v1.skill.metrics.GetMetricDataResponse>

Note that the optional arguments have a question mark after the name. Details on the arguments for this method are in the "Request parameters" table in the Metrics API documentation.

In the code sample, replace the arguments with your values and you'll get metrics information about the selected skill.

Get Started with the SMAPI SDK Today

The SMAPI SDK helps you bring the power of the Alexa SMAPI into apps and tools you build for yourself and your customers. Shout out to me at @YiddishNinja on Twitter and let me know if you found this helpful. Now go get coding with the SMAPI SDK.

Related Articles

Subscribe