Registry / azure / azure-eventgrid

azure-eventgrid

JSON →
library4.22.1pypypi✓ verified 24d ago

The Azure Event Grid client library for Python is used to publish events to Event Grid topics and to deserialize events received from Event Grid. It supports both the CloudEvents 1.0 schema and the Event Grid schema. The current version is 4.22.0, with frequent updates aligning with broader Azure SDK releases.

pip install azure-eventgrid
INSTALL
IMPORT
SIG · AZURE-EVENTGRID
A
azure-eventgrid
azurepythonv4.22.1
Install
2.4s avg
Import
432ms
Disk
23MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.22.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.460s · 24.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.404s · 25MB
23MB installed
● package 23MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

EventGridPublisherClient
from azure.eventgrid import EventGridPublisherClient
from azure.eventgrid import EventGridClient
EventGridClient was used in older V1 versions; EventGridPublisherClient is for current V4+.
EventGridDeserializer
from azure.eventgrid import EventGridDeserializer
CloudEvent
from azure.eventgrid import CloudEvent
from azure.eventgrid.models import CloudEvent
In V4+, EventGridEvent and CloudEvent are directly under azure.eventgrid, not a 'models' submodule.
EventGridEvent
from azure.eventgrid import EventGridEvent
from azure.eventgrid.models import EventGridEvent
In V4+, EventGridEvent and CloudEvent are directly under azure.eventgrid, not a 'models' submodule.
AzureKeyCredential
from azure.core.credentials import AzureKeyCredential

This quickstart demonstrates how to publish both CloudEvents and Event Grid Schema events to an Event Grid topic using `EventGridPublisherClient` and then how to deserialize incoming event payloads using `EventGridDeserializer`. Ensure `EVENT_GRID_ENDPOINT` and `EVENT_GRID_KEY` environment variables are set.

import os import json from azure.eventgrid import EventGridPublisherClient, EventGridEvent, CloudEvent, EventGridDeserializer from azure.core.credentials import AzureKeyCredential # Set your Event Grid endpoint and access key from environment variables EVENT_GRID_ENDPOINT = os.environ.get("EVENT_GRID_ENDPOINT", "") EVENT_GRID_KEY = os.environ.get("EVENT_GRID_KEY", "") if not EVENT_GRID_ENDPOINT or not EVENT_GRID_KEY: print("Please set the environment variables EVENT_GRID_ENDPOINT and EVENT_GRID_KEY.") exit(1) credential = AzureKeyCredential(EVENT_GRID_KEY) client = EventGridPublisherClient(EVENT_GRID_ENDPOINT, credential) # --- Publish a CloudEvent --- cloud_event = CloudEvent( source="https://example.com/myapp", type="Contoso.Items.ItemReceived", data={"itemSku": "CONTOSO-ITEM-0001", "itemCount": 1}, subject="MySubject", # Additional CloudEvent attributes can be passed as keyword arguments ) client.send([cloud_event]) print("Published a CloudEvent successfully.") # --- Publish an EventGridEvent --- event_grid_event = EventGridEvent( subject="Contoso/Items/ItemReceived", data={"itemSku": "CONTOSO-ITEM-0002", "itemCount": 1}, event_type="Contoso.Items.ItemReceived", data_version="1.0", ) client.send([event_grid_event]) print("Published an EventGridEvent successfully.") # --- Deserialize an incoming event (e.g., from a webhook payload) --- simulated_webhook_payload = json.dumps([ { "id": "test-event-id-1", "source": "/azure/events/test", "data": {"message": "Hello CloudEvent!"}, "type": "test.event", "time": "2023-10-27T10:00:00Z", "specversion": "1.0" }, { "id": "test-event-id-2", "topic": "/subscriptions/xxx/resourceGroups/yyy/providers/Microsoft.EventGrid/topics/mytesttopic", "subject": "TestSubject", "data": {"message": "Hello EventGridEvent!"}, "eventTime": "2023-10-27T10:05:00Z", "eventType": "Microsoft.Storage.BlobCreated", "dataVersion": "1.0", "metadataVersion": "1", "blobType": "BlockBlob" } ]) deserializer = EventGridDeserializer() deserialized_events = deserializer.deserialize_events(simulated_webhook_payload) print("\nDeserialized events from simulated webhook payload:") for event in deserialized_events: if isinstance(event, CloudEvent): print(f" CloudEvent - ID: {event.id}, Type: {event.type}, Data: {event.data}") elif isinstance(event, EventGridEvent): print(f" EventGridEvent - ID: {event.id}, Type: {event.event_type}, Subject: {event.subject}")
Debug
Known issues
breakingThe `azure-eventgrid` library underwent significant API changes between its V1 (1.x.x) and V4 (4.x.x) versions. Classes like `EventGridClient` for publishing and the `azure.eventgrid.models` submodule for event types (`EventGridEvent`, `CloudEvent`) were replaced.
fix
Upgrade to `azure-eventgrid>=4.0.0` and update your code. Use `EventGridPublisherClient` for publishing and import `EventGridEvent` or `CloudEvent` directly from `azure.eventgrid`.
affects: <4.0.0
gotchaEvent Grid supports two main event schemas: CloudEvents 1.0 and the Event Grid schema. You must correctly choose and construct the event type (`CloudEvent` or `EventGridEvent`) corresponding to the schema your Event Grid topic is configured to accept, or that you expect to receive. Mismatched schemas can lead to events being dropped or malformed.
fix
Carefully review your Event Grid topic's schema configuration and use the appropriate `CloudEvent` or `EventGridEvent` class. When publishing, the client will serialize events according to the object type provided. When deserializing, `EventGridDeserializer` can handle both.
affects: All
gotchaThere are two distinct Python libraries: `azure-eventgrid` (this data plane client) and `azure-mgmt-eventgrid` (the management plane client). `azure-eventgrid` is for sending/receiving actual events, while `azure-mgmt-eventgrid` is for creating, updating, and deleting Event Grid topics, domains, and subscriptions. Using the wrong library for your task will result in `AttributeError` or unexpected behavior.
fix
Ensure you import from `azure.eventgrid` for data plane operations (publishing/deserializing events) and `azure.mgmt.eventgrid` for resource management operations.
affects: All
gotchaWhen receiving events via HTTP (e.g., a webhook), Event Grid sends a 'webhook validation' event. Your application must respond to this validation event within 30 seconds by returning the 'validationCode' in the response body. Failing to do so will prevent the subscription from becoming active.
fix
Implement logic in your webhook endpoint to detect 'Microsoft.EventGrid.SubscriptionValidationEvent' and return a JSON response like `{'validationResponse': event.data['validationCode']}`.
affects: All
Errors
Common errors & fixes
Authentication Error / 401 Unauthorized / 403 Forbidden
This error typically occurs due to incorrect authentication credentials (e.g., invalid access key, expired SAS token), misconfigured Azure RBAC roles (e.g., missing 'Event Grid Data Sender' or 'Event Grid Data Receiver' role), or IP firewall restrictions on the Event Grid topic/domain.
fix
Verify that your Event Grid topic's access key or SAS token is correct and not expired. Ensure the identity publishing or consuming events has the appropriate RBAC role (e.g., 'Event Grid Data Sender' for publishing, 'Event Grid Data Receiver' for consuming) assigned. Check your Event Grid topic's IP firewall settings to ensure your client's IP address is allowed.
AttributeError: module 'azure.functions' has no attribute 'EventGridOutputEvent'
This error occurs when using an Azure Function with an Event Grid output binding, but the installed version of the `azure-functions` library (or the Azure Functions Core Tools) is outdated and does not include the necessary `EventGridOutputEvent` class.
fix
Update your `azure-functions` package to a version that supports Event Grid output bindings. If running locally with Azure Functions Core Tools, ensure it's updated to the latest version. For Python functions, ensure `azure-functions` and `azure-eventgrid` are specified in `requirements.txt` with compatible versions.
ImportError: cannot import name 'EventGridPublisherClient' from 'azure.eventgrid'
This error indicates that the `EventGridPublisherClient` class cannot be found within the `azure.eventgrid` module, often due to an incorrect or incomplete installation of the `azure-eventgrid` library or a versioning conflict with its dependencies like `azure-core`.
fix
Ensure that both `azure-eventgrid` and `azure-core` are correctly installed and up-to-date in your environment using `pip install --upgrade azure-eventgrid azure-core`. Verify your import statement: `from azure.eventgrid import EventGridPublisherClient`.
The attempt to validate the provided endpoint failed. For more details, visit https://aka.ms/esvalidation.
This error occurs during the creation of an Event Grid event subscription (especially for webhook endpoints) because Event Grid performs a handshake to validate the endpoint, and the endpoint did not respond correctly with the validation code or a 200 OK status.
fix
Ensure your webhook endpoint is publicly accessible and configured to handle Event Grid's subscription validation handshake. It must respond to an HTTP POST request containing a `SubscriptionValidationEvent` with the `validationCode` in the response body or respond to an HTTP OPTIONS request with a 200 OK status.
Upgrade
Version history
4.22.1latest on PyPI · released Jul 29, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
40 hits · last 30 days
node
34
OpenAI (training)
1
Resources
azure-eventgrid — pip install azure-eventgrid · libregistry