Azure Functions Bindings

Understanding Azure Functions Bindings

Azure Functions bindings provide a declarative way to connect to Azure services and other resources. They simplify your code by decoupling the implementation of your function from the details of interacting with external services. Bindings can be used for both triggers (which start your function) and for input and output data.

This page details the core concepts of triggers, input bindings, and output bindings in Azure Functions, along with practical examples.

Triggers

A trigger defines how a function is invoked. Each function must have exactly one trigger. When the event defined by the trigger occurs, Azure Functions runtime invokes your function.

Common Trigger Types:

Trigger Configuration Example (HTTP Trigger):

Triggers are typically configured in the function.json file or via attributes in your code (depending on your programming model).

{ "scriptFile": "run.csx", "bindings": [ { "authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, { "type": "http", "direction": "out", "name": "res" } ] }

C# Example (using attributes):


using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System.Net;

public static class HttpTriggerExample
{
    [Function("HttpTriggerExample")]
    public static async Task Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
        FunctionContext context)
    {
        var logger = context.GetLogger();
        logger.LogInformation("C# HTTP trigger function processed a request.");

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
        response.WriteString("Hello from Azure Functions!");

        return response;
    }
}
                

Input Bindings

Input bindings allow you to read data from other Azure services or external data sources within your function. The runtime retrieves the data based on the binding configuration and passes it as a parameter to your function.

Common Input Binding Scenarios:

Input Binding Configuration Example (Cosmos DB):

{ "scriptFile": "run.cs", "bindings": [ { "name": "myQueueItem", "type": "queueTrigger", "direction": "in", "queueName": "myqueue-items", "connection": "AzureWebJobsStorage" }, { "name": "product", "type": "cosmosDB", "direction": "in", "databaseName": "MyDatabase", "collectionName": "Products", "id": "{queueTrigger}", "partitionKey": "{queueTrigger}", "connectionStringSetting": "CosmosDbConnectionString" } ] }

C# Example (reading from Cosmos DB):


using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

public static class CosmosDbInputExample
{
    [Function("CosmosDbInputExample")]
    public static void Run(
        [QueueTrigger("myqueue-items")] string myQueueItem,
        [CosmosDB(
            databaseName: "MyDatabase",
            collectionName: "Products",
            Id = "{queueTrigger}",
            PartitionKey = "{queueTrigger}",
            ConnectionStringSetting = "CosmosDbConnectionString")] Product product,
        FunctionContext context)
    {
        var logger = context.GetLogger();
        logger.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

        if (product != null)
        {
            logger.LogInformation($"Retrieved Product: Id={product.Id}, Name={product.Name}");
            // Process the product data
        }
        else
        {
            logger.LogWarning($"Product not found for id: {myQueueItem}");
        }
    }
}

// Assume a simple Product class
public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    // Other properties
}
                

Output Bindings

Output bindings enable your function to write data to Azure services or other external data sources. Similar to input bindings, the runtime handles the service interaction based on the output binding configuration.

Common Output Binding Scenarios:

Output Binding Configuration Example (Service Bus):

{ "scriptFile": "run.js", "bindings": [ { "name": "triggerMessage", "type": "queueTrigger", "direction": "in", "queueName": "input-queue", "connection": "AzureWebJobsStorage" }, { "name": "outputSbQueue", "type": "serviceBus", "direction": "out", "queueName": "output-queue", "connection": "ServiceBusConnectionString" } ] }

JavaScript Example (writing to Service Bus):


module.exports = async function (context, triggerMessage) {
    context.log('JavaScript queue trigger function processed work item', triggerMessage);

    const outputMessage = {
        id: triggerMessage.id,
        processedData: "Some processed information",
        timestamp: new Date().toISOString()
    };

    context.bindings.outputSbQueue = outputMessage;
    context.log('Sent message to Service Bus output queue.');
};
                

Binding Expressions

Binding expressions are used within binding configurations to dynamically reference data from the trigger or other bindings. They are enclosed in curly braces {}.

These expressions make bindings highly flexible, allowing them to adapt to the specific data provided by the trigger event.

Key Takeaways

By leveraging Azure Functions bindings, you can build robust and scalable serverless applications with cleaner, more maintainable code.