Azure Event Grid trigger for Azure Functions

Use the function trigger to respond to an event sent to an event grid topic. To learn how to work with the Event Grid trigger.

For information on setup and configuration details, see the overview.

Note

Event Grid triggers aren't natively supported in an internal load balancer App Service Environment (ASE). The trigger uses an HTTP request that can't reach the function app without a gateway into the virtual network.

Example

For an HTTP trigger example, see Receive events to an HTTP endpoint.

The type of the input parameter used with an Event Grid trigger depends on these three factors:

  • Functions runtime version
  • Binding extension version
  • Modality of the C# function.

A C# function can be created using one of the following C# modes:

  • In-process class library: compiled C# function that runs in the same process as the Functions runtime.
  • Isolated process class library: compiled C# function that runs in a process isolated from the runtime. Isolated process is required to support C# functions running on .NET 5.0.
  • C# script: used primarily when creating C# functions in the Azure portal.

The following example shows a Functions version 3.x function that uses a CloudEvent binding parameter:

using Azure.Messaging;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class CloudEventTriggerFunction
    {
        [FunctionName("CloudEventTriggerFunction")]
        public static void Run(
            ILogger logger,
            [EventGridTrigger] CloudEvent e)
        {
            logger.LogInformation("Event received {type} {subject}", e.Type, e.Subject);
        }
    }
}

The following example shows a Functions version 3.x function that uses an EventGridEvent binding parameter:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class EventGridTriggerDemo
    {
        [FunctionName("EventGridTriggerDemo")]
        public static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());
        }
    }
}

The following example shows a function that uses a JObject binding parameter:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class EventGridTriggerCSharp
    {
        [FunctionName("EventGridTriggerCSharp")]
        public static void Run([EventGridTrigger] JObject eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.ToString(Formatting.Indented));
        }
    }
}

This section contains the following examples:

The following examples show trigger binding in Java that use the binding and generate an event, first receiving the event as String and second as a POJO.

Event Grid trigger, String parameter

  @FunctionName("eventGridMonitorString")
  public void logEvent(
    @EventGridTrigger(
      name = "event"
    )
    String content,
    final ExecutionContext context) {
      context.getLogger().info("Event content: " + content);
  }

Event Grid trigger, POJO parameter

This example uses the following POJO, representing the top-level properties of an Event Grid event:

import java.util.Date;
import java.util.Map;

public class EventSchema {

  public String topic;
  public String subject;
  public String eventType;
  public Date eventTime;
  public String id;
  public String dataVersion;
  public String metadataVersion;
  public Map<String, Object> data;

}

Upon arrival, the event's JSON payload is de-serialized into the EventSchema POJO for use by the function. This process allows the function to access the event's properties in an object-oriented way.

  @FunctionName("eventGridMonitor")
  public void logEvent(
    @EventGridTrigger(
      name = "event"
    )
    EventSchema event,
    final ExecutionContext context) {
      context.getLogger().info("Event content: ");
      context.getLogger().info("Subject: " + event.subject);
      context.getLogger().info("Time: " + event.eventTime); // automatically converted to Date by the runtime
      context.getLogger().info("Id: " + event.id);
      context.getLogger().info("Data: " + event.data);
  }

In the Java functions runtime library, use the EventGridTrigger annotation on parameters whose value would come from EventGrid. Parameters with these annotations cause the function to run when an event arrives. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.

The following example shows a trigger binding in a function.json file and a JavaScript function that uses the binding.

Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}

Here's the JavaScript code:

module.exports = async function (context, eventGridEvent) {
    context.log("JavaScript Event Grid function processed a request.");
    context.log("Subject: " + eventGridEvent.subject);
    context.log("Time: " + eventGridEvent.eventTime);
    context.log("Data: " + JSON.stringify(eventGridEvent.data));
};

The following example shows how to configure an Event Grid trigger binding in the function.json file.

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ]
}

The Event Grid event is made available to the function via a parameter named eventGridEvent, as shown in the following PowerShell example.

param($eventGridEvent, $TriggerMetadata)

# Make sure to pass hashtables to Out-String so they're logged correctly
$eventGridEvent | Out-String | Write-Host

The following example shows a trigger binding in a function.json file and a Python function that uses the binding.

Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "event",
      "direction": "in"
    }
  ],
  "disabled": false,
  "scriptFile": "__init__.py"
}

Here's the Python code:

import json
import logging

import azure.functions as func

def main(event: func.EventGridEvent):

    result = json.dumps({
        'id': event.id,
        'data': event.get_json(),
        'topic': event.topic,
        'subject': event.subject,
        'event_type': event.event_type,
    })

    logging.info('Python EventGrid trigger processed an event: %s', result)

Attributes

Both in-process and isolated process C# libraries use the EventGridTrigger attribute. C# script instead uses a function.json configuration file.

Here's an EventGridTrigger attribute in a method signature:

[FunctionName("EventGridTest")]
public static void EventGridTest([EventGridTrigger] JObject eventGridEvent, ILogger log)
{

Annotations

The EventGridTrigger annotation allows you to declaratively configure an Event Grid binding by providing configuration values. See the example and configuration sections for more detail.

Configuration

The following table explains the binding configuration properties that you set in the function.json file. There are no constructor parameters or properties to set in the EventGridTrigger attribute.

function.json property Description
type Required - must be set to eventGridTrigger.
direction Required - must be set to in.
name Required - the variable name used in function code for the parameter that receives the event data.

See the Example section for complete examples.

Usage

The parameter type supported by the Event Grid trigger depends on the Functions runtime version, the extension package version, and the C# modality used.

In-process C# class library functions supports the following types:

The Event Grid event instance is available via the parameter associated to the EventGridTrigger attribute, typed as an EventSchema.

The Event Grid instance is available via the parameter configured in the function.json file's name property.

The Event Grid instance is available via the parameter configured in the function.json file's name property, typed as func.EventGridEvent.

Event schema

Data for an Event Grid event is received as a JSON object in the body of an HTTP request. The JSON looks similar to the following example:

[{
  "topic": "/subscriptions/{subscriptionid}/resourceGroups/eg0122/providers/Microsoft.Storage/storageAccounts/egblobstore",
  "subject": "/blobServices/default/containers/{containername}/blobs/blobname.jpg",
  "eventType": "Microsoft.Storage.BlobCreated",
  "eventTime": "2018-01-23T17:02:19.6069787Z",
  "id": "{guid}",
  "data": {
    "api": "PutBlockList",
    "clientRequestId": "{guid}",
    "requestId": "{guid}",
    "eTag": "0x8D562831044DDD0",
    "contentType": "application/octet-stream",
    "contentLength": 2248,
    "blobType": "BlockBlob",
    "url": "https://egblobstore.blob.core.windows.net/{containername}/blobname.jpg",
    "sequencer": "000000000000272D000000000003D60F",
    "storageDiagnostics": {
      "batchId": "{guid}"
    }
  },
  "dataVersion": "",
  "metadataVersion": "1"
}]

The example shown is an array of one element. Event Grid always sends an array and may send more than one event in the array. The runtime invokes your function once for each array element.

The top-level properties in the event JSON data are the same among all event types, while the contents of the data property are specific to each event type. The example shown is for a blob storage event.

For explanations of the common and event-specific properties, see Event properties in the Event Grid documentation.

Next steps