Azure Functions Blob Output Bindings

Overview: This document explains how to use Azure Functions output bindings to write data to Azure Blob Storage. This allows your functions to easily store data without explicitly managing the Azure Storage SDK.

Introduction to Blob Output Bindings

Azure Functions provide declarative bindings that simplify common integration patterns. The Blob output binding allows your function to write data to a blob in an Azure Storage account. You define the binding in your function's function.json file (for JavaScript, Python, etc.) or via attributes (for C#, F#).

Configuring the Blob Output Binding

To use a Blob output binding, you need to define it in your function's configuration.

function.json Example (Node.js)


{
  "scriptFile": "index.js",
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [ "get", "post" ],
      "authLevel": "function"
    },
    {
      "name": "outputBlob",
      "type": "blob",
      "direction": "out",
      "path": "output-container/{name}.txt",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "res",
      "type": "http",
      "direction": "out"
    }
  ]
}
                

C# Example (using Attributes)


using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

public static class BlobOutputFunction
{
    [FunctionName("WriteToBlob")]
    public static async Task Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
        [Blob("output-container/{Query.name}.txt", FileAccess.Write, Connection = "AzureWebJobsStorage")] out string blobOutput)
    {
        string name = req.Query["name"];
        string requestBody = await new System.IO.StreamReader(req.Body).ReadToEndAsync();
        string content = name ?? requestBody;

        if (content != null)
        {
            blobOutput = content; // This writes to the blob
            return new OkObjectResult($"Successfully wrote to blob for name: {name}");
        }
        else
        {
            return new BadRequestObjectResult("Please pass a name in the query string or request body.");
        }
    }
}
                

Using the Blob Output Binding in Your Code

Once configured, you can write to the blob from your function's code. The way you do this depends on the language and runtime you are using.

Node.js Example


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. Your input was written to blob storage."
        : "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response and to write to blob storage.";

    context.bindings.outputBlob = name || "Default content for blob"; // Assign content to the output binding

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

Python Example


import logging
import azure.functions as func

def main(req: func.HttpRequest, outputBlob: func.Out[str]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        blob_content = f"Hello, {name}! This content was written to blob storage."
        outputBlob.set(blob_content) # Write to the blob
        return func.HttpResponse(
             f"Successfully wrote to blob for name: {name}",
             status_code=200
        )
    else:
        return func.HttpResponse(
             "Please pass a name in the query string or request body.",
             status_code=400
        )
                

Binding Parameters

The path parameter in the binding configuration is crucial. It defines the container and blob name where the data will be written. You can use tokens like {name}, {datetime}, etc., to dynamically name your blobs.

Blob Name Expressions

You can use dynamic expressions in the path to generate blob names. Common examples include:

Important: Ensure your connection setting points to a valid Azure Storage connection string in your function app's configuration.

Use Cases

By leveraging blob output bindings, you can significantly reduce the boilerplate code required for interacting with Azure Blob Storage, allowing you to focus on your core business logic.