Edit

Azure Service Bus output binding for Azure Functions

Use Azure Service Bus output binding to send queue or topic messages.

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 generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration 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

Go support isn't currently available for this binding.

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. Extensions for isolated worker process functions use Microsoft.Azure.Functions.Worker.Extensions.* namespaces.
  • In-process model: Compiled C# function that runs in the same process as the Functions runtime. In a variation of this model, Functions can be run using C# scripting, which is supported primarily for C# portal editing. Extensions for in-process functions use Microsoft.Azure.WebJobs.Extensions.* namespaces.

This code defines and initializes the ILogger:

private readonly ILogger<ServiceBusReceivedMessageFunctions> _logger;

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

This example shows a C# function that receives a message and writes it to a second queue:

[Function(nameof(ServiceBusReceivedMessageFunction))]
[ServiceBusOutput("outputQueue", Connection = "ServiceBusConnection")]
public string ServiceBusReceivedMessageFunction(
    [ServiceBusTrigger("queue", Connection = "ServiceBusConnection")] ServiceBusReceivedMessage message)
{
    _logger.LogInformation("Message ID: {id}", message.MessageId);
    _logger.LogInformation("Message Body: {body}", message.Body);
    _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);

    var outputMessage = $"Output message created at {DateTime.Now}";
    return outputMessage;
}

 


This example uses an HTTP trigger with an OutputType object to both send an HTTP response and write the output message.

[Function("HttpSendMsg")]
public async Task<OutputType> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext context)
{
   _logger.LogInformation($"C# HTTP trigger function processed a request for {context.InvocationId}.");

   HttpResponseData response = req.CreateResponse(HttpStatusCode.OK);
   await response.WriteStringAsync("HTTP response: Message sent");

   return new OutputType()
   {
       OutputEvent = "MyMessage",
       HttpResponse = response
   };
}

This code defines the multiple output type OutputType, which includes the Service Bus output binding definition on OutputEvent:

 public class OutputType
{
   [ServiceBusOutput("TopicOrQueueName", Connection = "ServiceBusConnection")]
   public string OutputEvent { get; set; }

   public HttpResponseData HttpResponse { get; set; }
}

The following example shows a Java function that sends a message to a Service Bus queue myqueue when triggered by an HTTP request.

@FunctionName("httpToServiceBusQueue")
@ServiceBusQueueOutput(name = "message", queueName = "myqueue", connection = "AzureServiceBusConnection")
public String pushToQueue(
  @HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
  final String message,
  @HttpOutput(name = "response") final OutputBinding<T> result ) {
      result.setValue(message + " has been sent.");
      return message;
 }

In the Java functions runtime library, use the @QueueOutput annotation on function parameters whose value would be written to a Service Bus queue. The parameter type should be OutputBinding<T>, where T is any native Java type of a plan old Java object (POJO).

Java functions can also write to a Service Bus topic. The following example uses the @ServiceBusTopicOutput annotation to describe the configuration for the output binding.

@FunctionName("sbtopicsend")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            @ServiceBusTopicOutput(name = "message", topicName = "mytopicname", subscriptionName = "mysubscription", connection = "ServiceBusConnection") OutputBinding<String> message,
            final ExecutionContext context) {

        String name = request.getBody().orElse("Azure Functions");

        message.setValue(name);
        return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();

    }

The following example shows a timer triggered TypeScript function that sends a queue message every 5 minutes.

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

export async function timerTrigger1(myTimer: Timer, context: InvocationContext): Promise<string> {
    const timeStamp = new Date().toISOString();
    return `Message created at: ${timeStamp}`;
}

app.timer('timerTrigger1', {
    schedule: '0 */5 * * * *',
    return: output.serviceBusQueue({
        queueName: 'testqueue',
        connection: 'MyServiceBusConnection',
    }),
    handler: timerTrigger1,
});

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

const timeStamp = new Date().toISOString();
const message = `Message created at: ${timeStamp}`;
return [`1: ${message}`, `2: ${message}`];

The following example shows a timer triggered JavaScript function that sends a queue message every 5 minutes.

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

const serviceBusOutput = output.serviceBusQueue({
    queueName: 'testqueue',
    connection: 'MyServiceBusConnection',
});

app.timer('timerTrigger1', {
    schedule: '0 */5 * * * *',
    return: serviceBusOutput,
    handler: (myTimer, context) => {
        const timeStamp = new Date().toISOString();
        return `Message created at: ${timeStamp}`;
    },
});

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

const timeStamp = new Date().toISOString();
const message = `Message created at: ${timeStamp}`;
return [`1: ${message}`, `2: ${message}`];

The following example shows a Service Bus output binding in a function.json file and a PowerShell function that uses the binding.

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

{
  "bindings": [
    {
      "type": "serviceBus",
      "direction": "out",
      "connection": "AzureServiceBusConnectionString",
      "name": "outputSbMsg",
      "queueName": "outqueue",
      "topicName": "outtopic"
    }
  ]
}

Here's the PowerShell that creates a message as the function's output.

param($QueueItem, $TriggerMetadata) 

Push-OutputBinding -Name outputSbMsg -Value @{ 
    name = $QueueItem.name 
    employeeId = $QueueItem.employeeId 
    address = $QueueItem.address 
} 

The following example demonstrates how to write out to a Service Bus topics and Service Bus queues in Python. The example depends on whether you use the v1 or v2 Python programming model.

This example shows how to write out to a Service Bus topic.

import logging
import azure.functions as func

app = func.FunctionApp()

@app.route(route="put_message")
@app.service_bus_topic_output(arg_name="message",
                              connection="AzureServiceBusConnectionString",
                              topic_name="outTopic")
def main(req: func.HttpRequest, message: func.Out[str]) -> func.HttpResponse:
    input_msg = req.params.get('message')
    message.set(input_msg)
    return 'OK'

This example shows how to write out to a Service Bus queue.

import azure.functions as func

app = func.FunctionApp()

@app.route(route="put_message")
@app.service_bus_queue_output(
    arg_name="msg",
    connection="AzureServiceBusConnectionString",
    queue_name="outqueue")
def put_message(req: func.HttpRequest, msg: func.Out[str]):
    msg.set(req.get_body().decode('utf-8'))
    return 'OK'

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 as described in the C# scripting guide.

In C# class libraries, use the ServiceBusOutputAttribute to define the queue or topic written to by the output.

The following table explains the properties you can set using the attribute:

Property Description
EntityType Sets the entity type as either Queue for sending messages to a queue or Topic when sending messages to a topic.
QueueOrTopicName Name of the topic or queue to send messages to. Use EntityType to set the destination type.
Connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.

Decorators

Applies only to the Python v2 programming model.

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

Property Description
arg_name The name of the variable that represents the queue or topic message in function code.
queue_name Name of the queue. Set only if sending queue messages, not for a topic.
topic_name Name of the topic. Set only if sending topic messages, not for a queue.
connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.

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

Annotations

The ServiceBusQueueOutput and ServiceBusTopicOutput annotations are available to write a message as a function output. The parameter decorated with these annotations must be declared as an OutputBinding<T> where T is the type corresponding to the message's type.

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

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.serviceBusQueue() method.

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

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

Property Description
topicName Name of the topic.
connection The name of an app setting or setting collection that specifies how to connect to Service Bus. 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 and the ServiceBus attribute.

function.json property Description
type Must be set to serviceBus. 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 or topic message in function code. Set to "$return" to reference the function return value.
queueName Name of the queue. Set only if sending queue messages, not for a topic.
topicName Name of the topic. Set only if sending topic messages, not for a queue.
connection The name of an app setting or setting collection that specifies how to connect to Service Bus. See Connections.
accessRights (v1 only) Access rights for the connection string. Available values are manage and listen. The default is manage, which indicates that the connection has the Manage permission. If you use a connection string that doesn't have the Manage permission, set accessRights to "listen". Otherwise, the Functions runtime might fail trying to do operations that require manage rights. In Azure Functions version 2.x and higher, this property isn't available because the latest version of the Service Bus SDK doesn't support manage operations.

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

All C# modalities and extension versions support the following output parameter types:

Type Description
System.String Use when the message to write is simple text. When the parameter value is null when the function exits, Functions doesn't create a message.
byte[] Use for writing binary data messages. When the parameter value is null when the function exits, Functions doesn't create a message.
Object When a message contains JSON, Functions serializes the object into a JSON message payload. When the parameter value is null when the function exits, Functions creates a message with a null object.

Messaging-specific parameter types contain extra message metadata and aren't compatible with JSON serialization. As a result, it isn't possible to use ServiceBusMessage with the output binding in the isolated model. The specific types supported by the output binding depend on the Functions runtime version, the extension package version, and the C# modality used.

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

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

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

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

For other output scenarios, create and use a ServiceBusClient with other types from Azure.Messaging.ServiceBus directly. See Register Azure clients for an example of using dependency injection to create a client type from the Azure SDK.

In Azure Functions 1.x, the runtime creates the queue if it doesn't exist and you have set accessRights to manage. In Azure Functions version 2.x and higher, the queue or topic must already exist; if you specify a queue or topic that doesn't exist, the function fails.

Use the Azure Service Bus SDK rather than the built-in output binding.

Access the output message by returning the value directly or using context.extraOutputs.set().

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

The output function parameter must be defined as func.Out[str] or func.Out[bytes]. Refer to the output example for details. Alternatively, you can use the Azure Service Bus SDK rather than the built-in output binding.

For a complete example, see the examples section.

Connections

The connection property is a reference to a key in application settings that returns a value used by the Functions runtime to connect to the Service Bus instance used by the extension. The value of the connection property setting depends on the type of connection:

  • Managed identity connection: The connection property is a <CONNECTION_NAME_PREFIX> shared by a group of settings that together define an identity-based connection to the Service Bus. For more information, see Define identity connections.
  • Key Vault reference: The connection property setting returns an Azure Key Vault reference to the location where the connection string is centrally maintained. For more information, see Define Key Vault connections.
  • App Configuration reference: The connection property setting returns an Azure App Configuration reference that returns a connection string or a Key Vault reference. For more information, see Azure App Configuration in the connections article.
  • Connection string: The connection property setting returns the actual connection string for the Service Bus instance. Because the connection string contains shared secret keys, you should consider using a managed identity connection, when possible. For more information, see Define connections.

To learn more about bindings connections, see Manage connection in Azure Functions.

To obtain a connection string, follow the steps shown at Get the management credentials. The connection string must be for a Service Bus namespace, not limited to a specific queue or topic.

If the app setting name begins with AzureWebJobs, you can specify only the remainder of the name. For example, if you set connection to MyServiceBus, the Functions runtime looks for an app setting named AzureWebJobsMyServiceBus. If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named AzureWebJobsServiceBus.

Scaling permissions

The Service Bus extension uses the Service Bus Administration API (GetQueueRuntimePropertiesAsync / GetSubscriptionRuntimePropertiesAsync) to retrieve accurate message counts for scale decisions. This API requires additional permissions beyond what is needed to send or receive messages:

  • SAS connection strings: The SAS policy must include the Manage access right.
  • Identity-based connections: The identity must be assigned the Azure Service Bus Data Owner role, or a custom role that includes Microsoft.ServiceBus/namespaces/*/read.

When the connection lacks these permissions you don't see errors at startup. Instead, the extension silently falls back to using peek-based message estimation, which is less accurate and could result in delayed or incorrect scaling decisions.

Tip

For production workloads that rely on auto-scaling, include the Manage access right (SAS) or assign the Azure Service Bus Data Owner role (identity-based connections) to ensure accurate scale behavior. connection string in the app setting that is named AzureWebJobsServiceBus.

Exceptions and return codes

Binding Reference
Service Bus Service Bus Error Codes
Service Bus Service Bus Limits

Next steps