HTTP Trigger

HTTP Triggers are a way to remotely invoke a workflow using a POST command. In other words, this is how you can get a workflow to start without touching a Relay device. An HTTP trigger can be initiated from anywhere in your enterprise, even outside of the Relay ecosystem.

For example, if you have a third-party Sales system, upon a new sale you could configure your Sales system to send an HTTP trigger to the Relay server to start a workflow that might do something like speak out information about that new sale on Relay devices.

This is one of the tools to easily integrate Relay into your enterprise, to extend your I/T applications to your active workers via Relay devices. You can use the HTTP trigger with parameters to have Relay be an output device for your other I/T applications.

Using a similar approach, conversely your Relay workflows can call back to your other I/T applications, whether it be via a webhook, or a third-party SDK you add to your workflow, to allow Relay to be an input device to your other I/T applications. Now you can have Relay devices participating in round-trip transactions.

📘

Helper Method Available

Included in the Relay SDK is a function that makes it easy to create and send an HTTP device info request, in a way that hides the network operations and authentication mechanics. The content below describes how to do it manually, but you'll probably want to use this helper method instead. See the fetchDevice method in the "Special Utilities" section on the Helper Methods page.

You can create an HTTP trigger to Relay from any application, or using a utility like curl:

$ curl -vv -X POST \
    -H "Authorization: Bearer $tokenp" \
    -H "User-Agent: my_client" \
    -H "Content-Type: application/json" \
    -d "{ 'action': 'invoke' }" \
    "https://all-main-pro-ibot.relaysvr.com/ibot/workflow/wf_httpsay_eGfOgo8Yb9CTkxKvk7K7m9AD?subscriber_id=7b28d9b0-4b46-41f8-910c-bcf8dac12345&user_id=99000756012345"

Because an HTTP trigger can come from anywhere, even outside of the Relay ecosystem, authentication is required via the Authorization header as described here: Auth. The User-Agent header is also described in the Auth page.

Let's walk through the creation of an HTTP trigger. First you'll create a workflow and host it. Here is a simple workflow that speaks 'Hello $deviceName':

import { relay, Event, createWorkflow, Uri } from '@relaypro/sdk'

const app = relay({port: 8080})

const helloWorkflow = createWorkflow(workflow => {
  const interactionName = 'hello interaction'

  workflow.on(Event.START, async (event) => {
    const { trigger: { args: { source_uri } } } = event
    await workflow.startInteraction([source_uri], interactionName)
  })

  workflow.on(Event.INTERACTION_STARTED, async ({ source_uri }) => {
    await workflow.sayAndWait(source_uri, 'hello world')
    await workflow.endInteraction([source_uri], interactionName)
  })

  workflow.on(Event.INTERACTION_ENDED, async() => {
    await workflow.terminate()
  })
})

app.workflow(`hellopath`, helloWorkflow)

Next, you will register your workflow against an HTTP trigger using the Relay CLI. Note the use of the http trigger type, and the POST method as type of method needed to cause the trigger. (POST is the only supported method for an HTTP trigger.)

$ relay workflow create http --trigger=POST --name message-http --uri wss://myappserver.mydomain.com/message --install 990007560012345

Your CLI command will return a workflow ID - which will be part of the URI that you'll call to trigger your workflow. Note: you must install a workflow on a device before you can trigger it via HTTP.

$ relay workflow list --extended
=== Installed Workflows
ID                                Name         Type      Uri                                    Args Installed on
wf_message_qQruCT57FebWVfyRuloP1B message-http http:POST wss://myappserver.mydomain.com/message      990007560012345

We'll also grab the Relay API URL to use as our base URL string:

$ relay env
=== ENVIRONMENT
api:         all-main-pro-ibot.relaysvr.com
auth:        auth.relaygo.com
auth_cli_id: 4EgeETYm
auth_sdk_id: RJZKRhh9
env:         qa

Next we'll add a call to our newly created HTTP trigger. Note, we're using an auth token created here and passing in a subscriber_id and user_id in the query string, which you can get from the CLI or Dash. The user_id specifies the ID sending device, and usually starts with 99000. The path part of the URL to append to base URL is /ibot/workflow/WORKFLOW_ID.

import axios from 'axios'
const sub_id = '7b28d9b0-4b46-41f8-910c-bcf8dac12345' //Your Subscriber ID
const workflow_id = 'wf_message_qQruCT57FebWVfyRuloP1B' //Your workflow id
const sending_device_id = '990007560012345' //Your Device ID
const _axios = axios.create()

const access_token = await refresh_auth()
_axios.defaults.headers.common['Authorization'] = 'Bearer ' + ${access_token}

async function send_relay_message() {
  let access_token = await get_access_token()
  try { 
    const response = await axios.post('https://all-main-pro-ibot.relaysvr.com/ibot/workflow/${workflow_id}?subscriber_id=${sub_id}&user_id=${sending_devicer_id}',
      { "action": "invoke" })
    if (response.status == 200) {
      console.log('HTTP trigger invoked!')
    }
  } catch (e) {
    console.error(e)
  }
  res.send('Received')
}

By default, this will run on the device that the workflow is invoked on (the user_id in the URL Params). You can target different devices to run the interactions on, which we'll cover in the section below.

Furthermore, if you want to pass arguments to your workflow via this http trigger, you can add those to the JSON payload under action_args where you have {'action': 'invoke'}. Be aware that all your values need to be strings (no integers, booleans, etc). For example:

{
      "action": "invoke", 
      "action_args": {
        "my_friend": "alice",
        "my_text": "this is a sample",
        "my_confirmation_required": "yes",
        "devices": "990007560047777,990007560025555"
        }
    }

...and then you can retrieve those action_args in the workflow in the trigger event in your handler for the start event:

const helloWorkflow = createWorkflow(workflow => {
  workflow.on(Event.START, async (event) => {
    console.log(`Event: ${JSON.stringify(event.trigger.args.args)}`)
    workflow.set({"friend": event.trigger.args.args.my_friend, 
            "text": event.trigger.args.args.my_text, 
            "confirm": event.trigger.args.args.my_confirmation_required})
  })

If you want to target multiple Relay endpoints with your HTTP trigger, pass in identifiers (could be Device IDs or Device Names) and then start an interaction for each. For example, the following takes in a comma delineated string of Relay Device IDs and starts an interaction for each:

const hellowWorkflow = createWorkflow(workflow => {
  workflow.on(Event.START, async (event) => {
    const { trigger: { args: { source_uri, args:{ devices } } } } = event
    const device_array = devices.split(',')
    device_array.forEach(async (element) => {
        const device_name = await workflow.getDeviceName(Uri.deviceId(element))
        await workflow.startInteraction(Uri.deviceName(device_name), `say${element}`)
    });
  })

  workflow.on(Event.INTERACTION_STARTED, async ({ source_uri: interaction_uri }) => {
    const deviceName = Uri.parseDeviceName(interaction_uri)
    const device = await workflow.getDeviceId(Uri.deviceName(deviceName))
    await workflow.sayAndWait(interaction_uri, `You are currently using ${deviceName}`)
  })
})

📘

Starting Interactions

You do need to start interactions with the name of the device instead of its numeric id.

The above example has the workflow installed to just one device, as we used the argument -i 990007560012345 in the relay workflow create http CLI command. If instead of installing to just one device, you instead used the --install-all option, or installed to multiple specific devices, then by default when you send a single http trigger (POST to the /ibot/workflow URL) then a workflow instance will be created for each installed device. This likely isn't what you want to have happen. So in this case to create only one workflow instance, you'll need to pick a device and then include that in the POST payload under the optional target_device_ids name/value pair, such as the following:

{
      "action": "invoke", 
      "target_device_ids": [ "990007560025555" ],
      "action_args": {
        "my_friend": "alice",
        "my_text": "this is a sample",
        "my_confirmation_required": "yes",
        }
    }

A workflow instance will be started for each device listed in target_device_ids.

Or as an alternative to using target_device_ids, you can install the workflow to just one device. If your HTTP-triggered workflow doesn't create any interactions, then it doesn't really matter which of your devices you install/run this workflow on.


Did this page help you?