Rediger

Del via


Twilio binding for Azure Functions

This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions supports output bindings for Twilio.

This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the following resources:

Install extension

The extension NuGet package you install depends on the C# mode you're using in your function app:

Functions execute in an isolated C# worker process. To learn more, see Guide for running C# Azure Functions in an isolated worker process.

The functionality of the extension varies depending on the extension version:

There is currently no support for Twilio for an isolated worker process app.

Install bundle

Starting with Functions version 2.x, the HTTP extension is part of an extension bundle, which is specified in your host.json project file. To learn more, see extension bundle.

This version of the extension should already be available to your function app with extension bundle, version 2.x.

Example

Unless otherwise noted, these examples are specific to version 2.x and later version of the Functions runtime.

A C# function can be created by using one of the following C# modes:

  • Isolated worker model: Compiled C# function that runs in a worker process that's isolated from the runtime. Isolated worker process is required to support C# functions running on LTS and non-LTS versions .NET and the .NET Framework.
  • In-process model: Compiled C# function that runs in the same process as the Functions runtime.
  • C# script: Used primarily when you create C# functions in the Azure portal.

The Twilio binding isn't currently supported for a function app running in an isolated worker process.

The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

Here's binding data in the function.json file:

Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSidSetting": "TwilioAccountSid",
  "authTokenSetting": "TwilioAuthToken",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

Here's the JavaScript code:

module.exports = async function (context, myQueueItem) {
    context.log('Node.js queue trigger function processed work item', myQueueItem);

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    var msg = "Hello " + myQueueItem.name + ", thank you for your order.";

    // Even if you want to use a hard coded message in the binding, you must at least
    // initialize the message binding.
    context.bindings.message = {};

    // A dynamic message can be set instead of the body in the output binding. The "To" number 
    // must be specified in code. 
    context.bindings.message = {
        body : msg,
        to : myQueueItem.mobileNumber
    };
};

Complete PowerShell examples aren't currently available for SendGrid bindings.

The following example shows how to send an SMS message using the output binding as defined in the following function.json.

    {
      "type": "twilioSms",
      "name": "twilioMessage",
      "accountSidSetting": "TwilioAccountSID",
      "authTokenSetting": "TwilioAuthToken",
      "from": "+1XXXXXXXXXX",
      "direction": "out",
      "body": "Azure Functions Testing"
    }

You can pass a serialized JSON object to the func.Out parameter to send the SMS message.

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, twilioMessage: func.Out[str]) -> func.HttpResponse:

    message = req.params.get('message')
    to = req.params.get('to')

    value = {
      "body": message,
      "to": to
    }

    twilioMessage.set(json.dumps(value))

    return func.HttpResponse(f"Message sent")

The following example shows how to use the TwilioSmsOutput annotation to send an SMS message. Values for to, from, and body are required in the attribute definition even if you override them programmatically.

package com.function;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

public class TwilioOutput {

    @FunctionName("TwilioOutput")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = { HttpMethod.GET, HttpMethod.POST },
                authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @TwilioSmsOutput(
                name = "twilioMessage",
                accountSid = "AzureWebJobsTwilioAccountSID",
                authToken = "AzureWebJobsTwilioAuthToken",
                to = "+1XXXXXXXXXX",
                body = "From Azure Functions",
                from = "+1XXXXXXXXXX") OutputBinding<String> twilioMessage,
            final ExecutionContext context) {

        String message = request.getQueryParameters().get("message");
        String to = request.getQueryParameters().get("to");

        StringBuilder builder = new StringBuilder()
            .append("{")
            .append("\"body\": \"%s\",")
            .append("\"to\": \"%s\"")
            .append("}");

        final String body = String.format(builder.toString(), message, to);

        twilioMessage.setValue(body);

        return request.createResponseBuilder(HttpStatus.OK).body("Message sent").build();
    }
}

Attributes

Both in-process and isolated worker process C# libraries use attributes to define the output binding. C# script instead uses a function.json configuration file.

The Twilio binding isn't currently supported for a function app running in an isolated worker process.

Annotations

The TwilioSmsOutput annotation allows you to declaratively configure the Twilio output binding by providing the following configuration values:

+

Place the TwilioSmsOutput annotation on an OutputBinding<T> parameter, where T may be any native Java type such as int, String, byte[], or a POJO type.

Configuration

The following table explains the binding configuration properties that you set in the function.json file, which differs by runtime version:

function.json property Description
type must be set to twilioSms.
direction must be set to out.
name Variable name used in function code for the Twilio SMS text message.
accountSidSetting This value must be set to the name of an app setting that holds your Twilio Account Sid (TwilioAccountSid). When not set, the default app setting name is AzureWebJobsTwilioAccountSid.
authTokenSetting This value must be set to the name of an app setting that holds your Twilio authentication token (TwilioAccountAuthToken). When not set, the default app setting name is AzureWebJobsTwilioAuthToken.
from This value is set to the phone number that the SMS text is sent from.
body This value can be used to hard code the SMS text message if you don't need to set it dynamically in the code for your function.

In version 2.x, you set the to value in your code.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Next steps