Skip to content

Latest commit

 

History

History
499 lines (371 loc) · 17.1 KB

functions-bindings-event-grid-trigger.md

File metadata and controls

499 lines (371 loc) · 17.1 KB
titledescriptionms.topicms.datems.devlangms.customzone_pivot_groups
Azure Event Grid trigger for Azure Functions
Learn to run code when Event Grid events in Azure Functions are dispatched.
reference
04/02/2023
csharp
devx-track-csharp, fasttrack-edit, devx-track-python, devx-track-extended-java, devx-track-js, devx-track-ts
programming-languages-set-functions

Azure Event Grid trigger for Azure Functions

Use the function trigger to respond to an event sent by an Event Grid source. You must have an event subscription to the source to receive events. To learn how to create an event subscription, see Create a subscription. For information on binding setup and configuration, 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.

::: zone pivot="programming-language-javascript,programming-language-typescript" [!INCLUDE functions-nodejs-model-tabs-description] ::: zone-end ::: zone pivot="programming-language-python" [!INCLUDE functions-bindings-python-models-intro]

::: zone-end

Example

::: zone pivot="programming-language-csharp"

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.

[!INCLUDE functions-bindings-csharp-intro]

[!INCLUDE functions-in-process-model-retirement-note]

When running your C# function in an isolated worker process, you need to define a custom type for event properties. The following example defines a MyEventType class.

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/EventGrid/EventGridFunction.cs" range="35-48":::

The following example shows how the custom type is used in both the trigger and an Event Grid output binding:

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/EventGrid/EventGridFunction.cs" range="11-33":::

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

usingAzure.Messaging;usingMicrosoft.Azure.WebJobs;usingMicrosoft.Azure.WebJobs.Extensions.EventGrid;usingMicrosoft.Extensions.Logging;namespaceCompany.Function{publicstaticclassCloudEventTriggerFunction{[FunctionName("CloudEventTriggerFunction")]publicstaticvoidRun(ILoggerlogger,[EventGridTrigger]CloudEvente){logger.LogInformation("Event received {type} {subject}",e.Type,e.Subject);}}}

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

usingMicrosoft.Azure.WebJobs;usingAzure.Messaging.EventGrid;usingMicrosoft.Azure.WebJobs.Extensions.EventGrid;usingMicrosoft.Extensions.Logging;namespaceCompany.Function{publicstaticclassEventGridTriggerDemo{[FunctionName("EventGridTriggerDemo")]publicstaticvoidRun([EventGridTrigger]EventGridEventeventGridEvent,ILoggerlog){log.LogInformation(eventGridEvent.Data.ToString());}}}

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

usingMicrosoft.Azure.WebJobs;usingMicrosoft.Azure.WebJobs.Extensions.EventGrid;usingNewtonsoft.Json;usingNewtonsoft.Json.Linq;usingMicrosoft.Extensions.Logging;namespaceCompany.Function{publicstaticclassEventGridTriggerCSharp{[FunctionName("EventGridTriggerCSharp")]publicstaticvoidRun([EventGridTrigger]JObjecteventGridEvent,ILoggerlog){log.LogInformation(eventGridEvent.ToString(Formatting.Indented));}}}

::: zone-end ::: zone pivot="programming-language-java"

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") publicvoidlogEvent( @EventGridTrigger( name = "event" ) Stringcontent, finalExecutionContextcontext) { 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:

importjava.util.Date; importjava.util.Map; publicclassEventSchema { publicStringtopic; publicStringsubject; publicStringeventType; publicDateeventTime; publicStringid; publicStringdataVersion; publicStringmetadataVersion; publicMap<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") publicvoidlogEvent( @EventGridTrigger( name = "event" ) EventSchemaevent, finalExecutionContextcontext) { context.getLogger().info("Event content: "); context.getLogger().info("Subject: " + event.subject); context.getLogger().info("Time: " + event.eventTime); // automatically converted to Date by the runtimecontext.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 Event Grid. 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>. ::: zone-end
::: zone pivot="programming-language-typescript"

The following example shows an event grid trigger TypeScript function.

:::code language="typescript" source="~/azure-functions-nodejs-v4/ts/src/functions/eventGridTrigger1.ts" :::

TypeScript samples are not documented for model v3.


::: zone-end ::: zone pivot="programming-language-javascript"

The following example shows an event grid trigger JavaScript function.

:::code language="javascript" source="~/azure-functions-nodejs-v4/js/src/functions/eventGridTrigger1.js" :::

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=asyncfunction(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));};

::: zone-end
::: zone pivot="programming-language-powershell"

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

::: zone-end
::: zone pivot="programming-language-python"
The following example shows an Event Grid trigger binding and a Python function that uses the binding. The example depends on whether you use the v1 or v2 Python programming model.

importloggingimportjsonimportazure.functionsasfuncapp=func.FunctionApp() @app.function_name(name="eventGridTrigger")@app.event_grid_trigger(arg_name="event")defeventGridTest(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)

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:

importjsonimportloggingimportazure.functionsasfuncdefmain(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)

::: zone-end
::: zone pivot="programming-language-csharp"

Attributes

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

Here's an EventGridTrigger attribute in a method signature:

:::code language="csharp" source="~/azure-functions-dotnet-worker/samples/Extensions/EventGrid/EventGridFunction.cs" range="13-16":::

Here's an EventGridTrigger attribute in a method signature:

[FunctionName("EventGridTest")]publicstaticvoidEventGridTest([EventGridTrigger]JObjecteventGridEvent,ILoggerlog){

::: zone-end
::: zone pivot="programming-language-java"

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. ::: zone-end
::: zone pivot="programming-language-javascript,programming-language-typescript"

Configuration

The options object passed to the app.eventGrid() method currently doesn't support any properties for model v4.

The following table explains the binding configuration properties that you set in the function.json file.

PropertyDescription
typeRequired - must be set to eventGridTrigger.
directionRequired - must be set to in.
nameRequired - the variable name used in function code for the parameter that receives the event data.

::: zone-end
::: zone pivot="programming-language-powershell,programming-language-python"

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 propertyDescription
typeRequired - must be set to eventGridTrigger.
directionRequired - must be set to in.
nameRequired - the variable name used in function code for the parameter that receives the event data.
::: zone-end

See the Example section for complete examples.

Usage

The Event Grid trigger uses a webhook HTTP request, which can be configured using the same host.json settings as the HTTP Trigger.

::: zone pivot="programming-language-csharp"
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:

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

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

[!INCLUDE functions-bindings-event-grid-trigger-dotnet-isolated-types]

Requires you to define a custom type, or use a string. See the Example section for examples of using a custom parameter type.

Functions version 1.x doesn't support the isolated worker process.


::: zone-end
::: zone pivot="programming-language-java" The Event Grid event instance is available via the parameter associated to the EventGridTrigger attribute, typed as an EventSchema. ::: zone-end
::: zone pivot="programming-language-powershell"
The Event Grid instance is available via the parameter configured in the function.json file's name property. ::: zone-end
::: zone pivot="programming-language-python"
The Event Grid instance is available via the parameter configured in the function.json file's name property, typed as func.EventGridEvent. ::: zone-end

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

close