Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • use modules in KRL
  • wrap an extermal API external API call and make it available from a module
  • use the keys pragma for API keys

...

For this lesson, we're going to be using the Twilio API to send SMS messages. Twilio provides a RESTful API for both voice and SMS interactions. Before you can complete this lesson, you'll need to register for a Twilio account. 

...

An SMS Action

Our first attempt will ignore some aspects of creating a useful module in order to just get something that works. Later we'll come back and clean those up. 

...

A user-defined action is similar to a KRL function in that its body consists of a set of declarations, but instead of the last line being an expression representing the return value, the last line is an action. We used the defaction() keyword to define the function. In our case, the action will be the http:post() action that POSTs to the Twilio API. Here's our action definition:

...

Code Block
languagejs
themeConfluence
linenumberstrue
ruleset io.picolabs.twilio_v2 {
  meta {

     configure using account_sid = ""
                    auth_token = ""
    
    provides 
        send_sms
  }

  global {
    
    send_sms = defaction(to, from, message) {
       base_url = "https://" + #{account_sid + ":" + }:#{auth_token} +
                      "@api.twilio.com/2010-04-01/Accounts/" + #{account_sid + "}/"
       http:post(base_url + "Messages.json")
            with form = {
                "From":from,
                "To":to,
                "Body":message
            }
    }
  }
}

...

We now have a Twilio module that wraps the Twilio API in functions and actions that are more convenient for KRL rulesets to use. We've also taken steps to protect sensative sensitive keys while making their use convenient. 

...