How can Alexa Call APIs?

In part 4 of this series on Alexa Account Linking we call the protected API of the linked account.

Let’s say we want to call the Spotify API in our Alexa Skill. The Spotify API is protected, it requires a user context. The user context needs to be established, and this is done with the Account Linking feature of Alexa.

The Spotify API should be connected via account linking and OAuth. After the user has linked the account, and an access token has been created, all request handlers receive the granted access token in the field

handlerInput.requestEnvelope.context.System.user.accessToken

We can use this token as a parameter when making API calls inside the request handler of an Alexa Skill. For example, we can call the Spotify API.

How can Alexa call APIs?

The following function is part of our Alexa Skill. It calls a protected API, actually the Spotify API, using the OAuth access token to get the user_id. Check out my video tutorial on calling the Spotify API.

async function getId(accessToken){
var user_url = "https://api.spotify.com/v1/me";
return request({url:user_url, headers:
{"Authorization":"Bearer "+accessToken}})
.then(function(res){
var user_id = JSON.parse(res).id;
return user_id;
});
}

Check out the other posts in this series on Alexa Account Linking:

In my new book “Making Money with Alexa Skills – A Developer’s Guide” I describe not only how to develop, but also how to monetize Alexa Skills. Account linking is one of the possibilities for personalizing a Skill and make it unique – more practical approaches for personalizing Alexa Skills are described in the Alexa Book.

In the OAuth 2.0 book you can find a simple and understandable explanation of all the standard OAuth Flows (such as those supported by Alexa). What makes this book unique is that the complicated OAuth interactions are visualized as easy-to-understand sequence diagrams.

Part 4 of Alexa Account Linking: How can Alexa Call APIs?

Also published on Medium.

Tagged on: