Getting Started with the SignalWire Communications API

What are SignalWire Communication APIs?

SignalWire Communication APIs are the next generation of interactive communication APIs that are easy to integrate to build any video application, voice application, and messaging application quickly with advanced command and control. It is a new, real-time web service protocol that provides for persistent, asynchronous connections to the SignalWire network - enabling the most responsive interactions and application logic.

Most providers use REST APIs that rely on one-way communication which adds latency and limits the interactivity of real-time events. SignalWire Communication APIs use WebSocket technology, which allows for simultaneous, bi-directional data transmission. Using SignalWire Communication APIs, you can deploy reliable, low latency, real-time communications.

SignalWire Communication APIs allow for interactive and advanced command and control. Complete control enables easy transfers and injections across all endpoints, making it easier and quicker to build applications. The APIs integrate easily with your products and infrastructure, enabling simple but powerful applications using Artificial Intelligence (AI) tools, data exchange, serverless technologies, and more.

Finally, SignalWire Communication APIs enable communications tools to perform in the most popular and widely used environments, like web browsers, mobile devices, in the cloud, or within your own infrastructure.

How do I get started?

It is easy to get started with SignalWire Communication API for video, API for voice, API for SMS with the SignalWire Communication APIs documentation which has links to the SDK for all languages we support: C#Node.JSRubyPHPPython, and Go.

You can install the SDK of your choice, or get started using our ready-to-go Docker images.

We will be basing the tutorial on the code contained in the latter repo.

What do I need?

If you would like to test this example out, the first thing to do is getting your SignalWire API keys.

1. Sign up

You can create a SignalWire account and space here.

Your account will start in trial mode, which you can exit by making a manual top-up of $5.00. You can find more information on the Trial Mode resource page.

If you are looking for more information about using SignalWire, refer to our Getting Started guide.

2. Get your credentials

Head to API in your dashboard and create a new token. Take note of the Project ID and token and keep it on hand for later.

3. Get a phone number

Set up a phone number to handle a call with SignalWire Communication APIs. Purchase a DID from the SignalWire dashboard, select "SignalWire Communication APIs" as the handler, and input office as the context.

SignalWire Communication APIs Consumer

The starting point for all SignalWire Communication API applications is a Consumer. This class encapsulates the main connection and call handling features, and makes it very easy to add real-time communications to your application.

In this article, we will be setting up our code for receiving a phone call.

Here is an example Consumer in various languages:

using System;

using SignalWire.Relay;
using SignalWire.Relay.Calling;

namespace ConsumerExample
{
    [Serializable]
    internal class PhoneConsumer : Consumer
    {        
        protected override void Setup()
        {

        }

        protected override void OnIncomingCall(Call call)
        {
            AnswerResult resultAnswer = call.Answer();
            if (!resultAnswer.Successful)
            {
            }
            else
            {
                // incoming call failed
            }

            call.PlayTTS("The quick brown fox jumps over the lazy dog.");
            TerminateCall(call);
        }

        public void TerminateCall(Call call)
        {
            call.Hangup();
        }
    }
}
const { RelayConsumer } = require('@signalwire/node')

const consumer = new RelayConsumer({
  project: process.env.SIGNALWIRE_PROJECT_KEY,
  token: process.env.SIGNALWIRE_TOKEN,
  contexts: ['office'],

  ready: async ({ client }) => {
    if (process.env.ENABLE_DEBUG) { 
      client.__logger.setLevel(client.__logger.levels.DEBUG)
    }
  },

  onIncomingCall: async (call) => {
    await call.answer()
    await call.playTTS({ text: 'Welcome to SignalWire!' });
    await call.hangup();
  }
})

consumer.run()
<?php
// PHP

require dirname(__FILE__) . '/vendor/autoload.php';

use Generator as Coroutine;
use SignalWire\Relay\Consumer;

class CustomConsumer extends Consumer {
  public $contexts = ['office'];

  public function setup() {
    $this->project = isset($_ENV['SIGNALWIRE_PROJECT_KEY']) ? $_ENV['SIGNALWIRE_PROJECT_KEY'] : '';
    $this->token = isset($_ENV['SIGNALWIRE_TOKEN']) ? $_ENV['SIGNALWIRE_TOKEN'] : '';
  }

  public function ready(): Coroutine {
    yield;
    // Consumer is successfully connected with Relay.
    // You can make calls or send messages here..
  }

  public function onIncomingCall($call): Coroutine {
    $result = yield $call->answer();
    if ($result->isSuccessful()) {
      yield $call->playTTS(['text' => 'Welcome to SignalWire!']);
    }
    yield $call->hangup();
  }
}

$consumer = new CustomConsumer();
$consumer->run();
from signalwire.relay.consumer import Consumer
import os

class CustomConsumer(Consumer):
  def setup(self):
    self.project = os.environ['SIGNALWIRE_PROJECT_KEY']
    self.token = os.environ['SIGNALWIRE_TOKEN']
    self.contexts = ['office']

  async def on_incoming_call(self, call):
    result = await call.answer()
    if result.successful:
      await call.play_tts(text='Welcome to SignalWire!')
      await call.hangup()

# Run your consumer..
consumer = CustomConsumer()
consumer.run()
require "signalwire"

Signalwire::Logger.logger.level = ::Logger::DEBUG if ENV['ENABLE_DEBUG']

class ::Consumer < Signalwire::Relay::Consumer
  contexts ['office']

  def on_incoming_call(call)
    call.answer
    call.play_tts text: 'Welcome to SignalWire'

    call.hangup
  end
end

::Consumer.new.run

Anatomy of a Consumer 

Looking at the Node.JS example in particular, we can see a few moving parts:

// We include the necessary class:

const { RelayConsumer } = require('@signalwire/node')

// We set up the consumer using the credentials from above. We also set ourselves up to wait for calls from the `office` context (more on that later).
const consumer = new RelayConsumer({
  project: process.env.SIGNALWIRE_PROJECT_KEY,
  token: process.env.SIGNALWIRE_TOKEN,
  contexts: ['office'],

 // We use one of the available event handlers to set up logging. Relay consumers provide `setup`, `ready`, and `teardown` to handle your specific requirements.

  ready: async ({ client }) => {
    if (process.env.ENABLE_DEBUG) { 
      client.__logger.setLevel(client.__logger.levels.DEBUG)
    }
  },

// We set up a specialized handler for controlling an incoming call.

  onIncomingCall: async (call) => {
    await call.answer()
    await call.playTTS({ text: 'Welcome to SignalWire!' });
    await call.hangup();
  }
})

// Finally, we just run the consumer.

consumer.run()

Running the consumer

To run the consumer using Docker, execute:

docker run -e SIGNALWIRE_PROJECT_KEY=<YOUR PROJECT> -e SIGNALWIRE_TOKEN=<YOUR TOKEN> -e ENABLE_DEBUG=true -v "/path/to/your/consumer.js:/app/consumer.js" signalwire/relay-example-node

You can find the complete Docker example here.

Deploying SignalWire Communication APIs

SignalWire Communication APIs run in their own processes, not within an HTTP server, and require no open ports, just an outbound connection to the SignalWire servers. This allows a Consumer to be very efficient, with a small footprint. The process can communicate with the other parts of your application using mechanisms such as REST, a processing queue, or using SignalWire Communication API Tasks, which we will touch on in Part 2.

Make a phone call!

Call the SignalWire number you purchased above, and hear the welcome!

Remember, if you are in Trial Mode, you will need to call in from a verified phone number or add $5 in credit to your account.

Resources

Please feel free to reach out to us on our Community Slack or create a Support ticket if you need guidance!

SignalWire in Seconds

If you want to see a live explanation of the SignalWire Communications API and how it differs from the Compatibility APIs, check out this video! If you want to learn more concepts about SignalWire in just a few short minutes each, check out our YouTube Channel!


Did this page help you?