Azure Functions Output Bindings - Event Grid

Azure Functions provides output bindings to integrate with various Azure services. The Event Grid output binding allows your functions to publish events to an Azure Event Grid topic.

Overview

When you configure an Event Grid output binding for your Azure Function, you can easily send event data to a specified Event Grid topic without needing to write explicit Event Grid SDK code within your function. This simplifies event publishing and promotes a reactive, event-driven architecture.

How it Works

The Event Grid output binding abstracts the process of creating and sending event payloads. You simply return a serializable object (like a POCO or a dictionary) from your function, or assign it to the output binding variable. The runtime handles serializing this object into the correct Event Grid event schema and delivering it to the configured Event Grid topic.

Configuration

To use the Event Grid output binding, you need to configure it in your function's function.json file.

function.json Example


{
  "scriptFile": "run.cs" // or run.ps1, index.js, etc.
  "bindings": [
    {
      "name": "msg",
      "type": "eventGrid",
      "direction": "out",
      "topicEndpoint": "%EVENTGRID_TOPIC_ENDPOINT%",
      "topicKey": "%EVENTGRID_TOPIC_KEY%"
    }
  ]
}
        

Binding Properties

Property Description Required
name The name of the output binding. This name is used to reference the binding in your function code. Yes
type Must be set to eventGrid. Yes
direction Must be set to out for output bindings. Yes
topicEndpoint The endpoint URL of the Event Grid topic. This can be provided directly or as an app setting reference (e.g., %EVENTGRID_TOPIC_ENDPOINT%). Yes
topicKey The key for authenticating to the Event Grid topic. This can be provided directly or as an app setting reference (e.g., %EVENTGRID_TOPIC_KEY%). Yes

Usage in Code

C# Example


using Microsoft.Azure.WebJobs;
using Microsoft.Azure.EventGrid.Models;
using System.Collections.Generic;

public static class PublishEventGridEvent
{
    [FunctionName("PublishEventGridEvent")]
    public static void Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req,
        [EventGrid(TopicEndpoint = "%EVENTGRID_TOPIC_ENDPOINT%", TopicKey = "%EVENTGRID_TOPIC_KEY%")] out EventGridEvent eventGridEvent)
    {
        // Example event data
        var eventData = new Dictionary<string, string>
        {
            { "message", "Hello from Azure Functions!" },
            { "source", "MyAzureFunction" }
        };

        eventGridEvent = new EventGridEvent
        {
            Id = System.Guid.NewGuid().ToString(),
            Topic = "/subscriptions/{your-subscription-id}/resourceGroups/{your-resource-group}/providers/Microsoft.EventGrid/topics/{your-topic-name}", // Or dynamically set
            Subject = "MyFunctionTrigger",
            EventType = "MyCustomEvent",
            EventTime = System.DateTime.UtcNow,
            Data = eventData,
            DataVersion = "1.0"
        };
    }
}
        

JavaScript Example (Node.js)


module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const eventData = {
        message: "Hello from Azure Functions!",
        source: "MyAzureFunction"
    };

    // The output binding 'eventGridOutput' is configured in function.json
    context.bindings.eventGridOutput = {
        id: context.bindingData.invocationId, // Or generate a new GUID
        topic: "/subscriptions/{your-subscription-id}/resourceGroups/{your-resource-group}/providers/Microsoft.EventGrid/topics/{your-topic-name}", // Or dynamically set
        subject: "MyFunctionTrigger",
        eventType: "MyCustomEvent",
        eventTime: new Date().toISOString(),
        data: eventData,
        dataVersion: "1.0"
    };

    context.res = {
        status: 200,
        body: "Event published to Event Grid"
    };
};
        

PowerShell Example


param($req)

$eventData = @{
    message = "Hello from Azure Functions!"
    source = "MyAzureFunction"
}

$event = @{
    Id = [guid]::NewGuid().ToString()
    Topic = "/subscriptions/{your-subscription-id}/resourceGroups/{your-resource-group}/providers/Microsoft.EventGrid/topics/{your-topic-name}" # Or dynamically set
    Subject = "MyFunctionTrigger"
    EventType = "MyCustomEvent"
    EventTime = Get-Date -UFormat %Y-%m-%dT%H:%M:%SZ
    Data = $eventData
    DataVersion = "1.0"
}

# The output binding 'eventGridOutput' is configured in function.json
$invocation = New-Object Microsoft.Azure.WebJobs.OutputBindings.ObjectFormatter.Invocation
$invocation.OutputBindings.Add("eventGridOutput", $event)

$context = New-Object Microsoft.Azure.WebJobs.Host.ScriptBindingContext
$context.OutputBindings = $invocation.OutputBindings

# Assign the event to the output binding context
$context.OutputBindings.Add("eventGridOutput", $event)


# Set the HTTP response
$req | Out-Object $context.OutputBindings.eventGridOutput # This syntax might need adjustment based on specific PowerShell Functions runtime behavior for direct output assignment

# For explicit assignment if the above is not direct:
# $context.OutputBindings["eventGridOutput"] = $event

# The runtime will pick up the eventGridOutput from context.OutputBindings

Write-Host "Published event to Event Grid."

# Return a simple HTTP response
Push-OutputBinding -Name "res" -Value @{
    status = 200
    body = "Event published to Event Grid"
}
        

Tip

When publishing multiple events, you can often return an array or collection of event objects. The binding will then publish each as a separate Event Grid event.

Event Grid Schema

The output binding expects or creates an object that conforms to the Event Grid event schema. Key properties include:

Important Considerations

Batching

For higher throughput scenarios, Azure Functions supports batching when publishing to Event Grid. If your binding is configured to accept an array or collection of events, the runtime can potentially batch multiple events into a single HTTP request to Event Grid, optimizing performance.

Related Topics