Azure Functions

Input and Output Bindings

Understanding Input and Output Bindings

Azure Functions bindings provide a declarative way to connect your function code to other Azure services and external data sources. They abstract away the complexities of client SDKs and connection management, allowing you to focus on your core logic.

Bindings fall into three main categories:

  • Trigger Bindings: Define what event initiates the function execution. A function can only have one trigger.
  • Input Bindings: Provide data to your function from a data source.
  • Output Bindings: Send data from your function to a data sink.

You configure bindings in your function.json file (or via attributes in C# or annotations in Java/Python). This configuration links your function parameters to specific data operations.

Input Bindings

Input bindings allow you to read data from a service or data source. When your function is triggered, the input binding will fetch the data and make it available as a parameter in your function signature.

For example, an input binding to Azure Blob Storage can retrieve a blob and provide its content as a string or stream to your function.

Example: Reading a blob with an input binding (function.json)


{
  "scriptFile": "run.csx",
  "entryPoint": "Run",
  "bindings": [
    {
      "name": "myTrigger",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [ "get", "post" ]
    },
    {
      "name": "inputBlob",
      "type": "blob",
      "direction": "in",
      "path": "mycontainer/{name}.txt",
      "connection": "AzureWebJobsStorage"
    },
    {
      "name": "outputBlob",
      "type": "blob",
      "direction": "out",
      "path": "outputcontainer/{name}.txt",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
                        

Example: Accessing input blob in C#


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

public static class BlobInputFunction
{
    [FunctionName("BlobInputFunction")]
    public static void Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        string name,
        Stream inputBlob, // This parameter receives the blob content
        [Blob("outputcontainer/{name}.txt", FileAccess.Write)] out string outputBlob,
        ILogger log)
    {
        log.LogInformation($"C# HTTP trigger function processed a request for blob: {name}.txt");

        if (inputBlob != null)
        {
            string blobContent = new StreamReader(inputBlob).ReadToEnd();
            log.LogInformation($"Blob content: {blobContent}");
            outputBlob = $"Processed content: {blobContent.ToUpper()}"; // Write to output blob
        }
        else
        {
            outputBlob = "Input blob not found.";
        }
    }
}
                        

Output Bindings

Output bindings allow your function to write data to a service or data sink. You typically define an output binding as a parameter in your function signature marked with the out keyword (in C#) or an output binding type in function.json.

Common uses include writing messages to an Azure Queue, saving data to Cosmos DB, or sending data to Event Hubs.

Example: Sending a message to a queue (function.json)


{
  "scriptFile": "run.py",
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [ "post" ]
    },
    {
      "name": "outputQueueItem",
      "type": "queue",
      "direction": "out",
      "queueName": "myqueue-items",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
                        

Example: Sending message to queue in Python


import logging
import azure.functions as func

def main(req: func.HttpRequest, outputQueueItem: 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:
        message = f"Hello, {name}! This HTTP triggered function executed successfully and created a queue message."
        outputQueueItem.set(message) # Set the output binding value
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )
                        

Trigger Bindings

While this page focuses on input and output bindings, it's important to remember that every function has a trigger. The trigger defines how the function is invoked.

Common triggers include HTTP triggers, Timer triggers, Blob triggers, Queue triggers, and Event Hub triggers. The trigger configuration is also part of the function.json.

Common Bindings and Their Usage

Azure Functions supports a wide range of bindings. Here are some of the most commonly used ones:

Blob Storage

Interact with Azure Blob Storage. You can read blobs as input or write blobs as output.

  • Input: type: "blob", direction: "in", path: "container/blobname"
  • Output: type: "blob", direction: "out", path: "container/blobname"

Cosmos DB

Connect to Azure Cosmos DB for NoSQL. You can read documents as input or write documents as output.

  • Input: type: "cosmosDB", direction: "in", databaseName, collectionName, id (for single document) or sqlQuery (for multiple documents).
  • Output: type: "cosmosDB", direction: "out", databaseName, collectionName.

Event Hubs

Ingest or send events to Azure Event Hubs.

  • Input: type: "eventHubTrigger", direction: "in", eventHubName, connection.
  • Output: type: "eventHub", direction: "out", eventHubName, connection.

Queue Storage

Read messages from or write messages to Azure Queue Storage.

  • Input: type: "queue", direction: "in", queueName, connection.
  • Output: type: "queue", direction: "out", queueName, connection.

Service Bus

Send or receive messages from Azure Service Bus queues and topics.

  • Input: type: "serviceBusTrigger", direction: "in", queueName or topicName, connection.
  • Output: type: "serviceBus", direction: "out", queueName or topicName, connection.

HTTP

Handle incoming HTTP requests (as a trigger) and return HTTP responses. Can also be used to make outbound HTTP calls.

  • Trigger: type: "httpTrigger", direction: "in".
  • Output: type: "http", direction: "out" (for returning an HttpResponse object).

Binding Expressions

Binding expressions allow you to dynamically configure bindings based on the trigger event or other function context. These expressions are enclosed in curly braces {}.

Common uses include:

  • Using trigger parameters in blob paths (e.g., "path": "input/{name}.txt" where {name} comes from an HTTP query parameter or route parameter).
  • Using system variables (e.g., %COMPUTERNAME%).
  • Accessing settings from local.settings.json or application settings (e.g., "connection": "MyBlobStorageConnection").

Binding expressions are powerful for creating flexible and dynamic data integrations.

Advanced Usage

Beyond basic input/output, bindings offer advanced features:

  • Collection Bindings: Read multiple items from a data source (e.g., multiple blobs, messages from a queue).
  • Batching: Triggers like Event Hubs and Service Bus can send events in batches to your function.
  • Custom Bindings: Develop your own custom bindings if the built-in ones don't meet your needs.
  • Multiple Bindings: Functions can have multiple input and output bindings to interact with various services simultaneously.