Azure Queue storage output bindings for Azure Functions

Azure Functions can create new Azure Queue storage messages by setting up an output binding.

For information on setup and configuration details, see the overview.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is currently in preview and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. Learn more about the differences between v3 and v4 in the upgrade guide.

Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.

The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see the Python developer guide.

This article supports both programming models.

Example

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

  • In-process class library: compiled C# function that runs in the same process as the Functions runtime.
  • Isolated worker process class library: compiled C# function that runs in a worker process that is isolated from the runtime. Isolated worker process is required to support C# functions running on non-LTS versions .NET and the .NET Framework.
  • C# script: used primarily when creating C# functions in the Azure portal.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Azure.Storage.Queues.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace SampleApp
{
    public class QueueFunction
    {
        private readonly ILogger<QueueFunction> _logger;

        public QueueFunction(ILogger<QueueFunction> logger)
        {
            _logger = logger;
        }

        //<docsnippet_queue_output_binding>
        //<docsnippet_queue_trigger>
        [Function(nameof(QueueFunction))]
        [QueueOutput("output-queue")]
        public string[] Run([QueueTrigger("input-queue")] Album myQueueItem, FunctionContext context)
        //</docsnippet_queue_trigger>
        {
            // Use a string array to return more than one message.
            string[] messages = {
                $"Album name = {myQueueItem.Name}",
                $"Album songs = {myQueueItem.Songs.ToString()}"};

            _logger.LogInformation("{msg1},{msg2}", messages[0], messages[1]);

            // Queue Output messages
            return messages;
        }
        //</docsnippet_queue_output_binding>

        /// <summary>
        /// This function demonstrates binding to a single <see cref="QueueMessage"/>.
        /// </summary>
        [Function(nameof(QueueMessageFunction))]
        public void QueueMessageFunction([QueueTrigger("input-queue")] QueueMessage message)
        {
            _logger.LogInformation(message.MessageText);
        }

        /// <summary>
        /// This function demonstrates binding to a single <see cref="BinaryData"/>.
        /// </summary>
        [Function(nameof(QueueBinaryDataFunction))]
        public void QueueBinaryDataFunction([QueueTrigger("input-queue")] BinaryData message)
        {
            _logger.LogInformation(message.ToString());
        }
    }

    public class Album
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public List<string> Songs { get; set; }
    }
}

For an end-to-end example of how to configure an output binding to Queue storage, see one of these articles:

The following example shows a Java function that creates a queue message for when triggered by an HTTP request.

@FunctionName("httpToQueue")
@QueueOutput(name = "item", queueName = "myqueue-items", connection = "MyStorageConnectionAppSetting")
 public String pushToQueue(
     @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
     final String message,
     @HttpOutput(name = "response") final OutputBinding<String> result) {
       result.setValue(message + " has been added.");
       return message;
 }

In the Java functions runtime library, use the @QueueOutput annotation on parameters whose value would be written to Queue storage. The parameter type should be OutputBinding<T>, where T is any native Java type of a POJO.

For an end-to-end example of how to configure an output binding to Queue storage, see one of these articles:

The following example shows an HTTP triggered TypeScript function that creates a queue item for each HTTP request received.

import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions';

const queueOutput = output.storageQueue({
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    const body = await request.text();
    context.extraOutputs.set(queueOutput, body);
    return { body: 'Created queue item.' };
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraOutputs: [queueOutput],
    handler: httpTrigger1,
});

To output multiple messages, return an array instead of a single object. For example:

import { app, HttpRequest, HttpResponseInit, InvocationContext, output } from '@azure/functions';

const queueOutput = output.storageQueue({
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    // <displayInDocs>
    context.extraOutputs.set(queueOutput, ['message 1', 'message 2']);
    // </displayInDocs>
    return { body: 'Created queue item.' };
}

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraOutputs: [queueOutput],
    handler: httpTrigger1,
});

The following example shows an HTTP triggered JavaScript function that creates a queue item for each HTTP request received.

const { app, output } = require('@azure/functions');

const queueOutput = output.storageQueue({
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
});

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraOutputs: [queueOutput],
    handler: async (request, context) => {
        const body = await request.text();
        context.extraOutputs.set(queueOutput, body);
        return { body: 'Created queue item.' };
    },
});

To output multiple messages, return an array instead of a single object. For example:

const { app, output } = require('@azure/functions');

const queueOutput = output.storageQueue({
    queueName: 'outqueue',
    connection: 'MyStorageConnectionAppSetting',
});

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraOutputs: [queueOutput],
    handler: async (request, context) => {
        // <displayInDocs>
        context.extraOutputs.set(queueOutput, ['message 1', 'message 2']);
        // </displayInDocs>
        return { body: 'Created queue item.' };
    },
});

For an end-to-end example of how to configure an output binding to Queue storage, see one of these articles:

The following code examples demonstrate how to output a queue message from an HTTP-triggered function. The configuration section with the type of queue defines the output binding.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "Msg",
      "queueName": "outqueue",
      "connection": "MyStorageConnectionAppSetting"
    }
  ]
}

Using this binding configuration, a PowerShell function can create a queue message using Push-OutputBinding. In this example, a message is created from a query string or body parameter.

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$message = $Request.Query.Message
Push-OutputBinding -Name Msg -Value $message
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = 200
    Body = "OK"
})

To send multiple messages at once, define a message array and use Push-OutputBinding to send messages to the Queue output binding.

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$message = @("message1", "message2")
Push-OutputBinding -Name Msg -Value $message
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = 200
    Body = "OK"
})

For an end-to-end example of how to configure an output binding to Queue storage, see one of these articles:

The following example demonstrates how to output single and multiple values to storage queues. The configuration needed for function.json is the same either way. The example depends on whether you use the v1 or v2 Python programming model.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.function_name(name="QueueOutput1")
@app.route(route="message")
@app.queue_output(arg_name="msg", 
                  queue_name="<QUEUE_NAME>", 
                  connection="<CONNECTION_SETTING>")
def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:
    input_msg = req.params.get('name')
    logging.info(input_msg)

    msg.set(input_msg)

    logging.info(f'name: {name}')
    return 'OK'

For an end-to-end example of how to configure an output binding to Queue storage, see one of these articles:

Attributes

The attribute that defines an output binding in C# libraries depends on the mode in which the C# class library runs.

When running in an isolated worker process, you use the QueueOutputAttribute, which takes the name of the queue, as shown in the following example:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using Azure.Storage.Queues.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

namespace SampleApp
{
    public class QueueFunction
    {
        private readonly ILogger<QueueFunction> _logger;

        public QueueFunction(ILogger<QueueFunction> logger)
        {
            _logger = logger;
        }

        //<docsnippet_queue_output_binding>
        //<docsnippet_queue_trigger>
        [Function(nameof(QueueFunction))]
        [QueueOutput("output-queue")]
        public string[] Run([QueueTrigger("input-queue")] Album myQueueItem, FunctionContext context)
        //</docsnippet_queue_trigger>
        {
            // Use a string array to return more than one message.
            string[] messages = {
                $"Album name = {myQueueItem.Name}",
                $"Album songs = {myQueueItem.Songs.ToString()}"};

            _logger.LogInformation("{msg1},{msg2}", messages[0], messages[1]);

            // Queue Output messages
            return messages;
        }
        //</docsnippet_queue_output_binding>

        /// <summary>
        /// This function demonstrates binding to a single <see cref="QueueMessage"/>.
        /// </summary>
        [Function(nameof(QueueMessageFunction))]
        public void QueueMessageFunction([QueueTrigger("input-queue")] QueueMessage message)
        {
            _logger.LogInformation(message.MessageText);
        }

        /// <summary>
        /// This function demonstrates binding to a single <see cref="BinaryData"/>.
        /// </summary>
        [Function(nameof(QueueBinaryDataFunction))]
        public void QueueBinaryDataFunction([QueueTrigger("input-queue")] BinaryData message)
        {
            _logger.LogInformation(message.ToString());
        }
    }

    public class Album
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public List<string> Songs { get; set; }
    }
}

Only returned variables are supported when running in an isolated worker process. Output parameters can't be used.

Decorators

Applies only to the Python v2 programming model.

For Python v2 functions defined using a decorator, the following properties on the queue_output:

Property Description
arg_name The name of the variable that represents the queue in function code.
queue_name The name of the queue.
connection The name of an app setting or setting collection that specifies how to connect to Azure Queues. See Connections.

For Python functions defined by using function.json, see the Configuration section.

Annotations

The QueueOutput annotation allows you to write a message as the output of a function. The following example shows an HTTP-triggered function that creates a queue message.

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

public class HttpTriggerQueueOutput {
    @FunctionName("HttpTriggerQueueOutput")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @QueueOutput(name = "message", queueName = "messages", connection = "MyStorageConnectionAppSetting") OutputBinding<String> message,
            final ExecutionContext context) {

        message.setValue(request.getQueryParameters().get("name"));
        return request.createResponseBuilder(HttpStatus.OK).body("Done").build();
    }
}
Property Description
name Declares the parameter name in the function signature. When the function is triggered, this parameter's value has the contents of the queue message.
queueName Declares the queue name in the storage account.
connection Points to the storage account connection string.

The parameter associated with the QueueOutput annotation is typed as an OutputBinding<T> instance.

Configuration

Applies only to the Python v1 programming model.

The following table explains the properties that you can set on the options object passed to the output.storageQueue() method.

Property Description
queueName The name of the queue.
connection The name of an app setting or setting collection that specifies how to connect to Azure Queues. See Connections.

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

The following table explains the binding configuration properties that you set in the function.json file.

function.json property Description
type Must be set to queue. This property is set automatically when you create the trigger in the Azure portal.
direction Must be set to out. This property is set automatically when you create the trigger in the Azure portal.
name The name of the variable that represents the queue in function code. Set to $return to reference the function return value.
queueName The name of the queue.
connection The name of an app setting or setting collection that specifies how to connect to Azure Queues. See Connections.

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

See the Example section for complete examples.

Usage

The usage of the Queue output binding depends on the extension package version and the C# modality used in your function app, which can be one of the following:

An isolated worker process class library compiled C# function runs in a process isolated from the runtime.

Choose a version to see usage details for the mode and version.

When you want the function to write a single message, the queue output binding can bind to the following types:

Type Description
string The message content as a string. Use when the message is simple text.
byte[] The bytes of the message.
JSON serializable types An object representing the content of a JSON message. Functions tries to serialize a plain-old CLR object (POCO) type into JSON data.

When you want the function to write multiple messages, the queue output binding can bind to the following types:

Type Description
T[] where T is one of the single message types An array containing content for multiple messages. Each entry represents one message.

For other output scenarios, create and use types from Azure.Storage.Queues directly.

There are two options for writing to a queue from a function by using the QueueOutput annotation:

  • Return value: By applying the annotation to the function itself, the return value of the function is written to the queue.

  • Imperative: To explicitly set the message value, apply the annotation to a specific parameter of the type OutputBinding<T>, where T is a POJO or any native Java type. With this configuration, passing a value to the setValue method writes the value to the queue.

Access the output queue item by returning the value directly or using context.extraOutputs.set(). You can use a string or a JSON-serializable object for the queue item payload.

Output to the queue message is available via Push-OutputBinding where you pass arguments that match the name designated by binding's name parameter in the function.json file.

There are two options for writing from your function to the configured queue:

  • Return value: Set the name property in function.json to $return. With this configuration, the function's return value is persisted as a Queue storage message.

  • Imperative: Pass a value to the set method of the parameter declared as an Out type. The value passed to set is persisted as a Queue storage message.

Connections

The connection property is a reference to environment configuration that specifies how the app should connect to Azure Queues. It may specify:

If the configured value is both an exact match for a single setting and a prefix match for other settings, the exact match is used.

Connection string

To obtain a connection string, follow the steps shown at Manage storage account access keys.

This connection string should be stored in an application setting with a name matching the value specified by the connection property of the binding configuration.

If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name here. For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "AzureWebJobsMyStorage." If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.

Identity-based connections

If you're using version 5.x or higher of the extension, instead of using a connection string with a secret, you can have the app use an Azure Active Directory identity. To use an identity, you define settings under a common prefix that maps to the connection property in the trigger and binding configuration.

If you're setting connection to "AzureWebJobsStorage", see Connecting to host storage with an identity. For all other connections, the extension requires the following properties:

Property Environment variable template Description Example value
Queue Service URI <CONNECTION_NAME_PREFIX>__queueServiceUri1 The data plane URI of the queue service to which you're connecting, using the HTTPS scheme. https://<storage_account_name>.queue.core.chinacloudapi.cn

1 <CONNECTION_NAME_PREFIX>__serviceUri can be used as an alias. If both forms are provided, the queueServiceUri form is used. The serviceUri form can't be used when the overall connection configuration is to be used across blobs, queues, and/or tables.

Other properties may be set to customize the connection. See Common properties for identity-based connections.

When hosted in the Azure Functions service, identity-based connections use a managed identity. The system-assigned identity is used by default, although a user-assigned identity can be specified with the credential and clientID properties. Note that configuring a user-assigned identity with a resource ID is not supported. When run in other contexts, such as local development, your developer identity is used instead, although this can be customized. See Local development with identity-based connections.

Grant permission to the identity

Whatever identity is being used must have permissions to perform the intended actions. For most Azure services, this means you need to assign a role in Azure RBAC, using either built-in or custom roles which provide those permissions.

Important

Some permissions might be exposed by the target service that are not necessary for all contexts. Where possible, adhere to the principle of least privilege, granting the identity only required privileges. For example, if the app only needs to be able to read from a data source, use a role that only has permission to read. It would be inappropriate to assign a role that also allows writing to that service, as this would be excessive permission for a read operation. Similarly, you would want to ensure the role assignment is scoped only over the resources that need to be read.

You will need to create a role assignment that provides access to your queue at runtime. Management roles like Owner are not sufficient. The following table shows built-in roles that are recommended when using the Queue Storage extension in normal operation. Your application may require additional permissions based on the code you write.

Binding type Example built-in roles
Trigger Storage Queue Data Reader, Storage Queue Data Message Processor
Output binding Storage Queue Data Contributor, Storage Queue Data Message Sender

Exceptions and return codes

Binding Reference
Queue Queue Error Codes
Blob, Table, Queue Storage Error Codes
Blob, Table, Queue Troubleshooting

Next steps