Azure Functions Documentation

Azure Functions Bindings Overview

Azure Functions enables you to build serverless applications by writing code that responds to events. Bindings are a declarative way to connect to Azure services and other resources without having to write boilerplate code to interact with them. This allows you to focus on your core business logic.

Bindings provide a way to declare how your function connects to data. They simplify your code by abstracting away the complexities of connecting to and interacting with various services like Azure Cosmos DB, Azure Storage, Azure Service Bus, and more. You declare bindings in your function's configuration file (e.g., function.json for JavaScript, C#, and F#, or attributes in C# code) and then use the bound data directly within your function code.

Key Concepts

Common Binding Types

Azure Functions supports a wide range of binding types for various services. Here are some of the most commonly used ones:

HTTP Trigger and Output Binding

The HTTP trigger allows your function to be invoked by an HTTP request. The HTTP output binding allows you to return an HTTP response.

Configuration (function.json example):

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

Code (JavaScript example):

module.exports = async function (context, req) {
    context.log('HTTP trigger function processed a request.');
    const name = (req.query.name || (req.body && req.body.name));
    const responseMessage = name
        ? 'Hello, ' + name + '!'
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.";

    context.res = {
        status: 200,
        body: responseMessage
    };
};

Blob Storage Input and Output Bindings

These bindings allow you to read from or write to Azure Blob Storage containers.

Configuration (function.json example):

{
  "bindings": [
    {
      "name": "myBlob",
      "type": "blob",
      "direction": "in",
      "path": "samples-workitems/{name}.txt",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputBlob",
      "type": "blob",
      "direction": "out",
      "path": "output-blobs/{name}.txt",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

Code (Node.js example):

module.exports = async function (context) {
    context.log('JavaScript blob trigger function processed blob', context.bindingData.name, context.bindingData.blobTrigger);
    context.log('Blob content:', context.bindings.myBlob);

    // Process the blob content and write to output blob
    context.bindings.outputBlob = `Processed content for ${context.bindingData.name}: ${context.bindings.myBlob}`;
    context.done();
};

Cosmos DB Input and Output Bindings

Interact with Azure Cosmos DB to read documents or write new ones.

Configuration (function.json example):

{
  "bindings": [
    {
      "name": "inputDocument",
      "type": "cosmosDB",
      "direction": "in",
      "databaseName": "Tasks",
      "collectionName": "Items",
      "id": "{id}",
      "partitionKey": "{id}",
      "connectionStringSetting": "CosmosDBConnection"
    },
    {
      "name": "outputDocument",
      "type": "cosmosDB",
      "direction": "out",
      "databaseName": "Tasks",
      "collectionName": "ProcessedItems",
      "connectionStringSetting": "CosmosDBConnection"
    }
  ]
}

Code (C# example):

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

public static class CosmosDbProcessor
{
    [FunctionName("CosmosDbProcessor")]
    public static void Run(
        [CosmosDBTrigger("Tasks", "Items", ConnectionStringSetting = "CosmosDBConnection",
            DatabaseName = "Tasks", CollectionName = "Items", CreateLeaseCollectionIfNotExists = true)] IReadOnlyList inputDocuments,
        [CosmosDB(
            databaseName: "Tasks",
            collectionName: "ProcessedItems",
            ConnectionStringSetting = "CosmosDBConnection")] out dynamic outputDocument,
        ILogger log)
    {
        log.LogInformation($"C# Script trigger function processed {inputDocuments.Count} documents.");
        foreach (var doc in inputDocuments)
        {
            log.LogInformation($"Processing document ID: {doc.id}");
            // Create a new document for the output collection
            outputDocument = new {
                id = Guid.NewGuid().ToString(),
                originalId = doc.id,
                processedData = $"Data from {doc.name} processed at {DateTime.UtcNow}"
            };
        }
    }
}

public class MyDocument
{
    public string id { get; set; }
    public string name { get; set; }
}

Queue Storage Trigger and Output Bindings

Functions can be triggered by messages arriving in an Azure Queue Storage queue, and can also send messages to a queue.

Configuration (function.json example):

{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "myqueue-items",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputQueue",
      "type": "queue",
      "direction": "out",
      "queueName": "output-queue",
      "connection": "AzureWebJobsStorage"
    }
  ]
}

Code (Python example):

import logging
import azure.functions as func

def main(myQueueItem: func.QueueMessage, outputQueue: func.Out[str]) -> None:
    logging.info('Python queue trigger function processed a queue item: %s',
                 myQueueItem.get_body().decode('utf-8'))
    message_body = myQueueItem.get_body().decode('utf-8')
    outputQueue.set(f"Processed: {message_body}")

Benefits of Using Bindings

Tip: Explore the full list of supported bindings in the official Azure Functions documentation to understand how you can integrate with a wide array of Azure services.

Further Reading