Azure Functions Bindings

Bindings are a declarative way to connect to other services without having to write extra code. They simplify the process of getting data into and out of your function.

What are Bindings?

In Azure Functions, bindings provide a way to declaratively connect your function code to Azure services (like storage, service bus, Cosmos DB, etc.) or other third-party services. They define how data flows into your function (as input parameters) and how data flows out of your function (as output).

Instead of writing boilerplate code to interact with these services, you define bindings in your function's configuration (usually a function.json file for older runtime versions or using attributes in code for newer versions). The Functions runtime handles the underlying connection and data transformation.

Types of Bindings

Bindings are categorized into two main types:

Triggers

A trigger is a specific type of input binding that causes your function to execute. Every function must have exactly one trigger. The trigger defines the event that will start your function's execution.

Input and Output Bindings

Input bindings allow you to read data from other services into your function as parameters. Output bindings allow you to write data to other services from your function. A function can have multiple input and output bindings.

Common Binding Scenarios

HTTP Trigger with Output Binding

A common scenario is an HTTP-triggered function that returns data. The HTTP trigger acts as the input, and an HTTP output binding sends a response back to the client.


// Example (JavaScript)
module.exports = async function (context, req) {
    context.log('JavaScript 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."
        : "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
    };
};
            

In this example:

Blob Trigger with Blob Output Binding

Process a blob when it's created in a storage container and then write a modified version to another container.


// Example (C#)
using System;
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

public static class ProcessBlob
{
    [FunctionName("ProcessBlob")]
    public static void Run([BlobTrigger("input-container/{name}", Connection = "AzureWebJobsStorage")] Stream inputBlob,
        [Blob("output-container/{name}", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream outputBlob,
        string name, ILogger log)
    {
        log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {inputBlob.Length} Bytes");

        // Example: Convert blob content to uppercase and write to output blob
        using (var reader = new StreamReader(inputBlob))
        using (var writer = new StreamWriter(outputBlob))
        {
            string content = reader.ReadToEnd();
            writer.Write(content.ToUpper());
        }
        log.LogInformation($"Processed blob and wrote to output-container/{name}");
    }
}
            

In this example:

Configuring Bindings

Binding configuration depends on the Azure Functions runtime version you are using.

Example function.json (Runtime v1.x)


{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "function"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}
        

Example Attributes (Runtime v2.x+ C#)

This is the same scenario as the function.json example above.


using System.Net;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

public static class HttpExample
{
    [FunctionName("HttpExample")]
    public static IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];
        if (string.IsNullOrEmpty(name))
        {
            name = req.Body.ToObject()?.name;
        }

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}
        

Benefits of Using Bindings

Key Takeaway: Bindings are fundamental to building efficient and maintainable Azure Functions by abstracting away the complexities of interacting with various data sources and services.