Microsoft Azure Event Grid Client Library for Python with publisher and consumer clients for both Event Grid Basic and Event Grid Namespaces
npx @tessl/cli install tessl/pypi-azure-eventgrid@4.22.00
# Azure Event Grid
1
2
Microsoft Azure Event Grid Client Library for Python provides comprehensive support for both Event Grid Basic (legacy) and Event Grid Namespaces. This library enables event-driven applications to publish events to Event Grid topics and consume events from Event Grid Namespace subscriptions using reliable, scalable event routing and processing capabilities.
3
4
## Package Information
5
6
- **Package Name**: azure-eventgrid
7
- **Language**: Python
8
- **Installation**: `pip install azure-eventgrid`
9
10
## Core Imports
11
12
```python
13
from azure.eventgrid import EventGridPublisherClient, EventGridConsumerClient
14
```
15
16
For async operations:
17
18
```python
19
from azure.eventgrid.aio import EventGridPublisherClient, EventGridConsumerClient
20
```
21
22
For legacy Event Grid Basic support:
23
24
```python
25
from azure.eventgrid import EventGridEvent, SystemEventNames, generate_sas
26
```
27
28
For models and data types:
29
30
```python
31
from azure.eventgrid.models import (
32
AcknowledgeResult, ReleaseResult, RejectResult, RenewLocksResult,
33
ReceiveDetails, BrokerProperties, ReleaseDelay
34
)
35
```
36
37
## Basic Usage
38
39
### Event Grid Namespaces (Modern)
40
41
```python
42
from azure.eventgrid import EventGridPublisherClient, EventGridConsumerClient
43
from azure.core.credentials import AzureKeyCredential
44
from azure.core.messaging import CloudEvent
45
46
# Publisher client for sending events
47
publisher = EventGridPublisherClient(
48
endpoint="https://namespace.region.eventgrid.azure.net",
49
credential=AzureKeyCredential("access_key"),
50
namespace_topic="my-topic"
51
)
52
53
# Create and send events
54
cloud_event = CloudEvent(
55
source="myapp/products",
56
type="Product.Created",
57
data={
58
"product_id": "12345",
59
"name": "New Product",
60
"price": 29.99
61
}
62
)
63
64
publisher.send([cloud_event])
65
publisher.close()
66
67
# Consumer client for receiving events
68
consumer = EventGridConsumerClient(
69
endpoint="https://namespace.region.eventgrid.azure.net",
70
credential=AzureKeyCredential("access_key"),
71
namespace_topic="my-topic",
72
subscription="my-subscription"
73
)
74
75
# Receive and process events
76
events = consumer.receive(max_events=10, max_wait_time=60)
77
for event_detail in events:
78
print(f"Event: {event_detail.event.type}")
79
print(f"Data: {event_detail.event.data}")
80
81
# Process the event, then acknowledge
82
# consumer.acknowledge(lock_tokens=[event_detail.broker_properties.lock_token])
83
84
consumer.close()
85
```
86
87
### Event Grid Basic (Legacy)
88
89
```python
90
from azure.eventgrid import EventGridPublisherClient, EventGridEvent
91
from azure.core.credentials import AzureKeyCredential
92
93
# Publisher client for Event Grid Basic
94
publisher = EventGridPublisherClient(
95
endpoint="https://my-topic.region.eventgrid.azure.net/api/events",
96
credential=AzureKeyCredential("access_key")
97
# No namespace_topic specified for Basic
98
)
99
100
# Create EventGrid schema event
101
event = EventGridEvent(
102
subject="products/product-123",
103
event_type="Product.Created",
104
data={
105
"product_id": "123",
106
"name": "Example Product"
107
},
108
data_version="1.0"
109
)
110
111
publisher.send([event])
112
publisher.close()
113
```
114
115
## Architecture
116
117
Azure Event Grid supports two distinct models:
118
119
- **Event Grid Basic**: Traditional domain/topic model with push delivery to webhooks, Event Hubs, Service Bus, and other endpoints
120
- **Event Grid Namespaces**: Modern pull-based model with MQTT support, dead lettering, and advanced message handling
121
122
The Python SDK provides unified client APIs for both models:
123
124
- **EventGridPublisherClient**: Publishes events to both Basic topics/domains and Namespace topics
125
- **EventGridConsumerClient**: Consumes events from Namespace subscriptions with pull delivery
126
- **Async Support**: Full async/await support for both publisher and consumer operations
127
- **Legacy Components**: Backward compatibility for existing Event Grid Basic applications
128
129
## Capabilities
130
131
### Event Publishing
132
133
Send events to Event Grid Basic topics/domains or Event Grid Namespace topics. Supports CloudEvent schema (namespaces), EventGrid schema (basic), and raw dictionaries with automatic content type detection.
134
135
```python { .api }
136
def send(
137
events: Union[CloudEvent, EventGridEvent, dict, List[Union[CloudEvent, EventGridEvent, dict]]],
138
*,
139
channel_name: Optional[str] = None,
140
content_type: Optional[str] = None,
141
**kwargs
142
) -> None: ...
143
```
144
145
[Event Publishing](./publisher.md)
146
147
### Event Consumption
148
149
Receive and manage events from Event Grid Namespace subscriptions with operations for acknowledging, releasing, rejecting, and renewing locks on events.
150
151
```python { .api }
152
def receive(
153
*,
154
max_events: Optional[int] = None,
155
max_wait_time: Optional[int] = None,
156
**kwargs
157
) -> List[ReceiveDetails]: ...
158
159
def acknowledge(*, lock_tokens: List[str], **kwargs) -> AcknowledgeResult: ...
160
def release(*, lock_tokens: List[str], release_delay: Optional[Union[int, ReleaseDelay]] = None, **kwargs) -> ReleaseResult: ...
161
def reject(*, lock_tokens: List[str], **kwargs) -> RejectResult: ...
162
def renew_locks(*, lock_tokens: List[str], **kwargs) -> RenewLocksResult: ...
163
```
164
165
[Event Consumption](./consumer.md)
166
167
### Async Operations
168
169
Asynchronous versions of all publisher and consumer operations for non-blocking event processing and high-throughput scenarios.
170
171
```python { .api }
172
async def send(
173
events: Union[CloudEvent, EventGridEvent, dict, List[Union[CloudEvent, EventGridEvent, dict]]],
174
*,
175
channel_name: Optional[str] = None,
176
content_type: Optional[str] = None,
177
**kwargs
178
) -> None: ...
179
180
async def receive(
181
*,
182
max_events: Optional[int] = None,
183
max_wait_time: Optional[int] = None,
184
**kwargs
185
) -> List[ReceiveDetails]: ...
186
```
187
188
[Async Operations](./async-operations.md)
189
190
### Models and Data Types
191
192
Response models, event metadata, broker properties, and enums for comprehensive event handling and status reporting.
193
194
```python { .api }
195
class ReceiveDetails:
196
broker_properties: BrokerProperties
197
event: CloudEvent
198
199
class BrokerProperties:
200
lock_token: str
201
delivery_count: int
202
203
class AcknowledgeResult:
204
failed_lock_tokens: List[FailedLockToken]
205
succeeded_lock_tokens: List[str]
206
```
207
208
[Models and Data Types](./models.md)
209
210
### Legacy Support
211
212
Event Grid Basic support with EventGrid schema events, system event names, and SAS token generation for backward compatibility.
213
214
```python { .api }
215
class EventGridEvent:
216
def __init__(
217
self,
218
subject: str,
219
event_type: str,
220
data: Any,
221
data_version: str,
222
*,
223
topic: Optional[str] = None,
224
metadata_version: Optional[str] = None,
225
id: Optional[str] = None,
226
event_time: Optional[datetime] = None
227
) -> None: ...
228
229
def generate_sas(
230
endpoint: str,
231
shared_access_key: str,
232
expiration_date_utc: datetime,
233
*,
234
api_version: Optional[str] = None
235
) -> str: ...
236
```
237
238
[Legacy Support](./legacy.md)
239
240
## Types
241
242
```python { .api }
243
from typing import List, Optional, Union, Any
244
from datetime import datetime
245
from azure.core.credentials import AzureKeyCredential, AzureSasCredential, TokenCredential
246
from azure.core.credentials_async import AsyncTokenCredential
247
from azure.core.messaging import CloudEvent
248
from azure.core.rest import HttpRequest, HttpResponse
249
250
# Authentication types
251
Credential = Union[AzureKeyCredential, AzureSasCredential, TokenCredential]
252
AsyncCredential = Union[AzureKeyCredential, AsyncTokenCredential]
253
254
# Event types for publishing
255
EventType = Union[CloudEvent, EventGridEvent, dict]
256
EventList = List[EventType]
257
SendableEvents = Union[EventType, EventList]
258
```