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.
- Examples: HTTP trigger (when an HTTP request is received), Timer trigger (on a schedule), Blob trigger (when a blob is created or updated), Queue trigger (when a message arrives in a queue).
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.
- Input Binding Examples: Reading data from a Cosmos DB document, fetching a blob's content, retrieving messages from a Service Bus topic.
- Output Binding Examples: Writing data to a Cosmos DB document, sending a message to a Service Bus queue, uploading a blob.
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:
reqis the input binding for the HTTP trigger.context.resis used to configure the HTTP output binding.
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:
[BlobTrigger("input-container/{name}")]is the input trigger.[Blob("output-container/{name}", FileAccess.Write)]is the output binding.
Configuring Bindings
Binding configuration depends on the Azure Functions runtime version you are using.
- Functions Runtime v1.x: Bindings are configured in a
function.jsonfile in the same directory as your function code. - Functions Runtime v2.x and later: Bindings are primarily configured using attributes directly in your code (e.g., C#, Java, PowerShell) or through decorators (e.g., Python). This approach offers better compile-time checking and IDE support.
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
- Reduced Boilerplate: Focus on your business logic, not service integration code.
- Declarative Configuration: Easily define data flow and service connections.
- Extensibility: Supports a wide range of Azure services and custom bindings.
- Maintainability: Clear separation of concerns makes code easier to understand and manage.
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.