Azure Event Grid trigger for Azure Functions

Use the function trigger to respond to an event sent to an Event Grid topic.

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. 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.

Version 3.x

The following example shows a Functions 3.x C# function that binds to a CloudEvent:

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 3.x C# function that binds to an EventGridEvent:

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

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

C# (2.x and higher)

The following example shows a C# function that binds to EventGridEvent:

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
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());
        }
    }
}

For more information, see Packages, Attributes, Configuration, and Usage.

Version 1.x

The following example shows a Functions 1.x C# function that binds to JObject:

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));
        }
    }
}

Attributes and annotations

In C# class libraries, use the EventGridTrigger attribute.

Here's an EventGridTrigger attribute in a method signature:

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

For a complete example, see C# example.

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.

Usage

In Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

  • JObject
  • string

In Azure Functions 2.x and higher, you also have the option to use the following parameter type for the Event Grid trigger:

  • Microsoft.Azure.EventGrid.Models.EventGridEvent- Defines properties for the fields common to all event types.

Note

If you try to bind to Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, the compiler displays a "deprecated" message and advises you to use Microsoft.Azure.EventGrid.Models.EventGridEvent instead. To use the newer type, reference the Microsoft.Azure.EventGrid NuGet package and fully qualify the EventGridEvent type name by prefixing it with Microsoft.Azure.EventGrid.Models.

Additional types

Apps using the 3.0.0 or higher version of the Event Grid extension use the EventGridEvent type from the Azure.Messaging.EventGrid namespace. In addition, you can bind to the CloudEvent type from the Azure.Messaging namespace.

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.

The EventGridEvent type defines only the top-level properties; the Data property is a JObject.

Create a subscription

To start receiving Event Grid HTTP requests, create an Event Grid subscription that specifies the endpoint URL that invokes the function.

Azure portal

For functions that you develop in the Azure portal with the Event Grid trigger, select Integration then choose the Event Grid Trigger and select Create Event Grid subscription.

Connect a new event subscription to trigger in the portal.

When you select this link, the portal opens the Create Event Subscription page with the current trigger endpoint already defined.

Create event subscription with function endpoint already defined

For more information about how to create subscriptions by using the Azure portal, see Create custom event - Azure portal in the Event Grid documentation.

Azure CLI

To create a subscription by using the Azure CLI, use the az eventgrid event-subscription create command.

The command requires the endpoint URL that invokes the function. The following example shows the version-specific URL pattern:

Version 2.x (and higher) runtime

https://{functionappname}.azurewebsites.net/runtime/webhooks/eventgrid?functionName={functionname}&code={systemkey}

Version 1.x runtime

https://{functionappname}.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName={functionname}&code={systemkey}

The system key is an authorization key that has to be included in the endpoint URL for an Event Grid trigger. The following section explains how to get the system key.

Here's an example that subscribes to a blob storage account (with a placeholder for the system key):

Version 2.x (and higher) runtime

az eventgrid resource event-subscription create -g myResourceGroup \
    --provider-namespace Microsoft.Storage --resource-type storageAccounts \
    --resource-name myblobstorage12345 --name myFuncSub \
    --included-event-types Microsoft.Storage.BlobCreated \
    --subject-begins-with /blobServices/default/containers/images/blobs/ \
    --endpoint https://mystoragetriggeredfunction.azurewebsites.net/runtime/webhooks/eventgrid?functionName=imageresizefunc&code=<key>

Version 1.x runtime

az eventgrid resource event-subscription create -g myResourceGroup \
    --provider-namespace Microsoft.Storage --resource-type storageAccounts \
    --resource-name myblobstorage12345 --name myFuncSub \
    --included-event-types Microsoft.Storage.BlobCreated \
    --subject-begins-with /blobServices/default/containers/images/blobs/ \
    --endpoint https://mystoragetriggeredfunction.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName=imageresizefunc&code=<key>

For more information about how to create a subscription, see the blob storage quickstart or the other Event Grid quickstarts.

Get the system key

You can get the system key by using the following API (HTTP GET):

Version 2.x (and higher) runtime

http://{functionappname}.azurewebsites.net/admin/host/systemkeys/eventgrid_extension?code={masterkey}

Version 1.x runtime

http://{functionappname}.azurewebsites.net/admin/host/systemkeys/eventgridextensionconfig_extension?code={masterkey}

This is an admin API, so it requires your function app master key. Don't confuse the system key (for invoking an Event Grid trigger function) with the master key (for performing administrative tasks on the function app). When you subscribe to an Event Grid topic, be sure to use the system key.

Here's an example of the response that provides the system key:

{
  "name": "eventgridextensionconfig_extension",
  "value": "{the system key for the function}",
  "links": [
    {
      "rel": "self",
      "href": "{the URL for the function, without the system key}"
    }
  ]
}

You can get the master key for your function app from the Function app settings tab in the portal.

Important

The master key provides administrator access to your function app. Don't share this key with third parties or distribute it in native client applications.

For more information, see Authorization keys in the HTTP trigger reference article.

Alternatively, you can send an HTTP PUT to specify the key value yourself.

Local testing with viewer web app

To test an Event Grid trigger locally, you have to get Event Grid HTTP requests delivered from their origin in the cloud to your local machine. One way to do that is by capturing requests online and manually resending them on your local machine:

  1. Create a viewer web app that captures event messages.
  2. Create an Event Grid subscription that sends events to the viewer app.
  3. Generate a request and copy the request body from the viewer app.
  4. Manually post the request to the localhost URL of your Event Grid trigger function.

When you're done testing, you can use the same subscription for production by updating the endpoint. Use the az eventgrid event-subscription update Azure CLI command.

Create a viewer web app

To simplify capturing event messages, you can deploy a pre-built web app that displays the event messages. The deployed solution includes an App Service plan, an App Service web app, and source code from GitHub.

Select Deploy to Azure to deploy the solution to your subscription. In the Azure portal, provide values for the parameters.

Button to Deploy to Azure.

The deployment may take a few minutes to complete. After the deployment has succeeded, view your web app to make sure it's running. In a web browser, navigate to: https://<your-site-name>.azurewebsites.net

You see the site but no events have been posted to it yet.

View new site

Create an Event Grid subscription

Create an Event Grid subscription of the type you want to test, and give it the URL from your web app as the endpoint for event notification. The endpoint for your web app must include the suffix /api/updates/. So, the full URL is https://<your-site-name>.azurewebsites.net/api/updates

For information about how to create subscriptions by using the Azure portal, see Create custom event - Azure portal in the Event Grid documentation.

Generate a request

Trigger an event that will generate HTTP traffic to your web app endpoint. For example, if you created a blob storage subscription, upload or delete a blob. When a request shows up in your web app, copy the request body.

The subscription validation request will be received first; ignore any validation requests, and copy the event request.

Copy request body from web app

Manually post the request

Run your Event Grid function locally. The Content-Type and aeg-event-type headers are required to be manually set, while and all other values can be left as default.

Use a tool such as Postman or curl to create an HTTP POST request:

  • Set a Content-Type: application/json header.
  • Set an aeg-event-type: Notification header.
  • Paste the RequestBin data into the request body.
  • Post to the URL of your Event Grid trigger function.
    • For 2.x and higher use the following pattern:

      http://localhost:7071/runtime/webhooks/eventgrid?functionName={FUNCTION_NAME}
      
    • For 1.x use:

      http://localhost:7071/admin/extensions/EventGridExtensionConfig?functionName={FUNCTION_NAME}
      

The functionName parameter must be the name specified in the FunctionName attribute.

The following screenshots show the headers and request body in Postman:

Headers in Postman

Request body in Postman

The Event Grid trigger function executes and shows logs similar to the following example:

Sample Event Grid trigger function logs

Next steps