GitHub Copilot ChatGPT Claude Codex CLI Cursor opencode Skill Text

azure-eventgrid-py

Azure Event Grid SDK for Python. Use for publishing events, handling CloudEvents, and event-driven architectures. Triggers: "event grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events".

Ciza · 0 points · 21 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download microsoft-skills-.github_plugins_azure-sdk-python_skills_azure-eventgrid-py-e58528d.zip · 4 KB
Part of microsoft/skills — 195 skills

Install

skills CLI npx skills add https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-eventgrid-py
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install microsoft-skills@llmmart
Git git clone https://github.com/microsoft/skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole microsoft/skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Azure Event Grid SDK for Python

Event routing service for building event-driven applications with pub/sub semantics.

Installation

pip install azure-eventgrid azure-identity

Environment Variables

EVENTGRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events  # Required for Event Grid topic publishing
EVENTGRID_NAMESPACE_ENDPOINT=https://<namespace>.<region>.eventgrid.azure.net  # Required for namespace operations
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production

Authentication & Lifecycle

🔑 Two rules apply to every code sample below:

  1. Prefer DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
    • Local dev: DefaultAzureCredential works as-is.
    • Production: set AZURE_TOKEN_CREDENTIALS=prod (or AZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.
  2. Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
    • Sync: with <Client>(...) as client:
    • Async: async with <Client>(...) as client: and async with DefaultAzureCredential() as credential: (from azure.identity.aio)

Snippets may abbreviate this setup, but production code should always follow both rules.

import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.eventgrid import EventGridPublisherClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

endpoint = "https://<topic-name>.<region>.eventgrid.azure.net/api/events"

with EventGridPublisherClient(endpoint, credential) as client:
    # Use client here (see following sections for operations)
    ...

Event Types

Format Class Use Case
Cloud Events 1.0 CloudEvent Standard, interoperable (recommended)
Event Grid Schema EventGridEvent Azure-native format

Publish CloudEvents

from azure.eventgrid import EventGridPublisherClient, CloudEvent
from azure.identity import DefaultAzureCredential

with EventGridPublisherClient(endpoint, DefaultAzureCredential()) as client:
    # Single event
    event = CloudEvent(
        type="MyApp.Events.OrderCreated",
        source="/myapp/orders",
        data={"order_id": "12345", "amount": 99.99}
    )
    client.send(event)

    # Multiple events
    events = [
        CloudEvent(
            type="MyApp.Events.OrderCreated",
            source="/myapp/orders",
            data={"order_id": f"order-{i}"}
        )
        for i in range(10)
    ]
    client.send(events)

Publish EventGridEvents

from azure.eventgrid import EventGridEvent
from datetime import datetime, timezone

event = EventGridEvent(
    subject="/myapp/orders/12345",
    event_type="MyApp.Events.OrderCreated",
    data={"order_id": "12345", "amount": 99.99},
    data_version="1.0"
)

client.send(event)

Event Properties

CloudEvent Properties

event = CloudEvent(
    type="MyApp.Events.ItemCreated",      # Required: event type
    source="/myapp/items",                 # Required: event source
    data={"key": "value"},                 # Event payload
    subject="items/123",                   # Optional: subject/path
    datacontenttype="application/json",   # Optional: content type
    dataschema="https://schema.example",  # Optional: schema URL
    time=datetime.now(timezone.utc),      # Optional: timestamp
    extensions={"custom": "value"}         # Optional: custom attributes
)

EventGridEvent Properties

event = EventGridEvent(
    subject="/myapp/items/123",            # Required: subject
    event_type="MyApp.ItemCreated",        # Required: event type
    data={"key": "value"},                 # Required: event payload
    data_version="1.0",                    # Required: schema version
    topic="/subscriptions/.../topics/...", # Optional: auto-set
    event_time=datetime.now(timezone.utc)  # Optional: timestamp
)

Async Client

from azure.eventgrid.aio import EventGridPublisherClient
from azure.identity.aio import DefaultAzureCredential

async def publish_events():
    credential = DefaultAzureCredential()
    
    async with EventGridPublisherClient(endpoint, credential) as client:
        event = CloudEvent(
            type="MyApp.Events.Test",
            source="/myapp",
            data={"message": "hello"}
        )
        await client.send(event)

import asyncio
asyncio.run(publish_events())

Namespace Topics (Event Grid Namespaces)

For Event Grid Namespaces (pull delivery):

from azure.eventgrid import EventGridPublisherClient
from azure.identity import DefaultAzureCredential

# Namespace endpoint (different from custom topic)
namespace_endpoint = "https://<namespace>.<region>.eventgrid.azure.net"
topic_name = "my-topic"

with EventGridPublisherClient(
    endpoint=namespace_endpoint,
    credential=DefaultAzureCredential()
) as client:
    client.send(
        event,
        namespace_topic=topic_name
    )

Best Practices

  1. Pick sync OR async and stay consistent. Do not mix azure.xxx sync clients with azure.xxx.aio async clients in the same call path. Choose one mode per module.
  2. Always use context managers for clients and async credentials. Wrap every client in with Client(...) as client: (sync) or async with Client(...) as client: (async). For async DefaultAzureCredential from azure.identity.aio, also use async with credential: so tokens and transports are cleaned up.
  3. Use DefaultAzureCredential for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
  4. Use CloudEvents for new applications (industry standard)
  5. Batch events when publishing multiple events
  6. Include meaningful subjects for filtering
  7. Use async client for high-throughput scenarios
  8. Handle retries — Event Grid has built-in retry
  9. Set appropriate event types for routing and filtering

Reference Files

File Contents
references/capabilities.md Additional non-hero capabilities, operation-group coverage, and production checklists.
references/non-hero-scenarios.md Dedicated non-hero examples for secondary/advanced scenarios.
Files (skills)
  • references
    • capabilities.md 1.3 KB
      # azure-eventgrid-py capability coverage
      
      **SDK/package**: `azure-eventgrid`
      
      This index maps hero scenarios in `SKILL.md` and links non-hero scenarios documented in dedicated reference files.
      
      ## Hero scenarios covered in SKILL.md
      
      - `Event Types`
      - `Publish CloudEvents`
      - `Publish EventGridEvents`
      - `Event Properties`
      
      ## Non-hero scenarios
      
      - `Async Client`: Dedicated example and implementation notes.  
        See: [`non-hero-scenarios.md#async-client`](non-hero-scenarios.md#async-client)
      - `Namespace Topics (Event Grid Namespaces)`: For Event Grid Namespaces (pull delivery):  
        See: [`non-hero-scenarios.md#namespace-topics-event-grid-namespaces`](non-hero-scenarios.md#namespace-topics-event-grid-namespaces)
      
      ## Related deep-dive references
      
      - [`non-hero-scenarios.md`](non-hero-scenarios.md): Dedicated non-hero examples and implementation notes.
      
      ## API breadth checklist
      
      - Verify client/auth mode for the environment before coding.
      - Confirm operation-group/method names against current Microsoft Learn API reference.
      - For Python SDKs with both sync and async clients, document both forms without a blanket preference.
      - Include cleanup/delete paths for created resources in examples.
      - Prefer idempotent create/update operations where available.
      - Validate paging/LRO/error-handling patterns for production paths.
      
    • non-hero-scenarios.md 1.6 KB
      # azure-eventgrid-py non-hero scenarios
      
      These scenarios are intentionally separate from hero flows in `SKILL.md`.
      They cover secondary/advanced patterns typically used after the primary end-to-end path is working.
      
      ## Async Client
      
      ```python
      from azure.core.messaging import CloudEvent
      from azure.eventgrid.aio import EventGridPublisherClient
      from azure.identity.aio import DefaultAzureCredential
      
      async def publish_events():
          async with DefaultAzureCredential() as credential:
              async with EventGridPublisherClient(endpoint, credential) as client:
                  event = CloudEvent(
                      type="MyApp.Events.Test",
                      source="/myapp",
                      data={"message": "hello"}
                  )
                  await client.send(event)
      
      import asyncio
      asyncio.run(publish_events())
      ```
      
      ## Namespace Topics (Event Grid Namespaces)
      
      For Event Grid Namespaces (pull delivery):
      
      ```python
      from azure.core.messaging import CloudEvent
      from azure.eventgrid import EventGridPublisherClient
      from azure.identity import DefaultAzureCredential
      
      # Namespace endpoint (different from custom topic)
      namespace_endpoint = "https://<namespace>.<region>.eventgrid.azure.net"
      topic_name = "my-topic"
      
      with DefaultAzureCredential() as credential:
          with EventGridPublisherClient(
              endpoint=namespace_endpoint,
              credential=credential,
              namespace_topic=topic_name,
          ) as client:
              event = CloudEvent(
                  type="MyApp.Events.Test",
                  source="/myapp",
                  data={"message": "hello from namespace"}
              )
              client.send(event)
      ```
      
  • SKILL.md 7.2 KB
    ---
    name: azure-eventgrid-py
    description: |
      Azure Event Grid SDK for Python. Use for publishing events, handling CloudEvents, and event-driven architectures.
      Triggers: "event grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events".
    license: MIT
    metadata:
      author: Microsoft
      version: "1.0.0"
      package: azure-eventgrid
    ---
    
    # Azure Event Grid SDK for Python
    
    Event routing service for building event-driven applications with pub/sub semantics.
    
    ## Installation
    
    ```bash
    pip install azure-eventgrid azure-identity
    ```
    
    ## Environment Variables
    
    ```bash
    EVENTGRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events  # Required for Event Grid topic publishing
    EVENTGRID_NAMESPACE_ENDPOINT=https://<namespace>.<region>.eventgrid.azure.net  # Required for namespace operations
    AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
    ```
    
    ## Authentication & Lifecycle
    
    > **🔑 Two rules apply to every code sample below:**
    >
    > 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
    >    - Local dev: `DefaultAzureCredential` works as-is.
    >    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
    > 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
    >    - Sync: `with <Client>(...) as client:`
    >    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
    >
    > Snippets may abbreviate this setup, but production code should always follow both rules.
    
    ```python
    import os
    from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
    from azure.eventgrid import EventGridPublisherClient
    
    # Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
    credential = DefaultAzureCredential(require_envvar=True)
    # Or use a specific credential directly in production:
    # See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
    # credential = ManagedIdentityCredential()
    
    endpoint = "https://<topic-name>.<region>.eventgrid.azure.net/api/events"
    
    with EventGridPublisherClient(endpoint, credential) as client:
        # Use client here (see following sections for operations)
        ...
    ```
    
    ## Event Types
    
    | Format | Class | Use Case |
    |--------|-------|----------|
    | Cloud Events 1.0 | `CloudEvent` | Standard, interoperable (recommended) |
    | Event Grid Schema | `EventGridEvent` | Azure-native format |
    
    ## Publish CloudEvents
    
    ```python
    from azure.eventgrid import EventGridPublisherClient, CloudEvent
    from azure.identity import DefaultAzureCredential
    
    with EventGridPublisherClient(endpoint, DefaultAzureCredential()) as client:
        # Single event
        event = CloudEvent(
            type="MyApp.Events.OrderCreated",
            source="/myapp/orders",
            data={"order_id": "12345", "amount": 99.99}
        )
        client.send(event)
    
        # Multiple events
        events = [
            CloudEvent(
                type="MyApp.Events.OrderCreated",
                source="/myapp/orders",
                data={"order_id": f"order-{i}"}
            )
            for i in range(10)
        ]
        client.send(events)
    ```
    
    ## Publish EventGridEvents
    
    ```python
    from azure.eventgrid import EventGridEvent
    from datetime import datetime, timezone
    
    event = EventGridEvent(
        subject="/myapp/orders/12345",
        event_type="MyApp.Events.OrderCreated",
        data={"order_id": "12345", "amount": 99.99},
        data_version="1.0"
    )
    
    client.send(event)
    ```
    
    ## Event Properties
    
    ### CloudEvent Properties
    
    ```python
    event = CloudEvent(
        type="MyApp.Events.ItemCreated",      # Required: event type
        source="/myapp/items",                 # Required: event source
        data={"key": "value"},                 # Event payload
        subject="items/123",                   # Optional: subject/path
        datacontenttype="application/json",   # Optional: content type
        dataschema="https://schema.example",  # Optional: schema URL
        time=datetime.now(timezone.utc),      # Optional: timestamp
        extensions={"custom": "value"}         # Optional: custom attributes
    )
    ```
    
    ### EventGridEvent Properties
    
    ```python
    event = EventGridEvent(
        subject="/myapp/items/123",            # Required: subject
        event_type="MyApp.ItemCreated",        # Required: event type
        data={"key": "value"},                 # Required: event payload
        data_version="1.0",                    # Required: schema version
        topic="/subscriptions/.../topics/...", # Optional: auto-set
        event_time=datetime.now(timezone.utc)  # Optional: timestamp
    )
    ```
    
    ## Async Client
    
    ```python
    from azure.eventgrid.aio import EventGridPublisherClient
    from azure.identity.aio import DefaultAzureCredential
    
    async def publish_events():
        credential = DefaultAzureCredential()
        
        async with EventGridPublisherClient(endpoint, credential) as client:
            event = CloudEvent(
                type="MyApp.Events.Test",
                source="/myapp",
                data={"message": "hello"}
            )
            await client.send(event)
    
    import asyncio
    asyncio.run(publish_events())
    ```
    
    ## Namespace Topics (Event Grid Namespaces)
    
    For Event Grid Namespaces (pull delivery):
    
    ```python
    from azure.eventgrid import EventGridPublisherClient
    from azure.identity import DefaultAzureCredential
    
    # Namespace endpoint (different from custom topic)
    namespace_endpoint = "https://<namespace>.<region>.eventgrid.azure.net"
    topic_name = "my-topic"
    
    with EventGridPublisherClient(
        endpoint=namespace_endpoint,
        credential=DefaultAzureCredential()
    ) as client:
        client.send(
            event,
            namespace_topic=topic_name
        )
    ```
    
    ## Best Practices
    
    1. **Pick sync OR async and stay consistent.** Do not mix `azure.xxx` sync clients with `azure.xxx.aio` async clients in the same call path. Choose one mode per module.
    2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
    3. **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
    4. **Use CloudEvents** for new applications (industry standard)
    5. **Batch events** when publishing multiple events
    6. **Include meaningful subjects** for filtering
    7. **Use async client** for high-throughput scenarios
    8. **Handle retries** — Event Grid has built-in retry
    9. **Set appropriate event types** for routing and filtering
    
    ## Reference Files
    
    | File | Contents |
    |------|----------|
    | [references/capabilities.md](references/capabilities.md) | Additional non-hero capabilities, operation-group coverage, and production checklists. |
    | [references/non-hero-scenarios.md](references/non-hero-scenarios.md) | Dedicated non-hero examples for secondary/advanced scenarios. |
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related