Apprentice and the API Call

Create your own voice command for Google Assistant with Python, Dialogflow and Google Cloud Functions (serverless!) [Part 2]

Andrew Graham-Yooll
2 min readDec 20, 2018
Apprentice. Allowing easy development for Google Actions.

In the previous section, we initialized and ran our webhook code with a local development server. To expose the server to the web, we ran a ngrok http tunnel to which allowed a user intent in the Google Assistant console to interact with the webhook.

The following steps will execute an API call in the Apprentice webhook and return a joke to the user.

Step 1: Same Page

Test the intent tell me a joke just to make sure we are on the same page.

It should return “Hello World.”

If not, go back to our previous section and see what’s going wrong. If you need help debugging, leave a comment with a good issue description and I’ll see what I can do to help. 👍

Step 2: The Joke

Instead of writing our own jokes, we are going to be using an API called icanhazdadjoke.

icanhazdadjoke has a very straight forward API. The call is a simple GET which returns a joke. We don’t have to deal with extra parameters or authentication to use it, so it will be a perfect API for our action.

The below is the code for the dad joke API call in main.py:

import requestsfrom apprentice import Apprenticeapr = Apprentice(__name__)@apr.route('/', methods=['POST'])def webhook(*args, **kwargs):    reply = get_joke_repsonse()    return apr.generate_text_response(reply)
def get_joke_repsonse():
headers = {'Accept': 'text/plain'} joke = requests.get('https://icanhazdadjoke.com/', headers=headers) return joke.text.rstrip()

Once a POST to the webhook is called, it will call the joke API.

Then the joke is returned to the action via the generate_text_response method of Apprentice. This will format a basic text response adhering to the Dialogflow API 2.0 specifications.

Step 3: Test Again

Once our local development server has detected changes in our files and restarts automatically, we can run the intent again in our Google Assistant console.

If successful we should see a dad joke!

HAR HAR HAR HAR!

Conclusion

In this section we learned how to write the API call for our Google Assistant Action.

The next section will focus on the deployment to the Google Cloud Function and Alpha Releasing.

Why would you want that?

Well, suppose you were to close your computer right now. The local ngrok process would stop and so would the development server. That would break your action, and no one could use it!

So lets get deploying!

--

--