Publishing and Handling Custom Events
This lesson explains custom topics, event design, publishing from Python with keyless authentication, and handler validation.
Learning outcomes
After completing this lesson, you will be able to:
- Describe how a custom topic is created and secured.
- Explain good event type and subject design.
- Describe publishing with EventGridPublisherClient.
- Explain webhook endpoint validation.
Creating a custom topic
A custom topic is an Azure resource with an endpoint such as https://TOPIC.REGION-1.eventgrid.azure.net/api/events. When it is created, its input schema is chosen: CloudEvents 1.0, the Event Grid schema, or a custom schema with a mapping to the Event Grid fields. Publishers authenticate with Microsoft Entra ID, which needs the EventGrid Data Sender role on the topic, or with an access key or SAS token; local (key) authentication can be disabled to require Entra ID.
az eventgrid topic create --resource-group RG --name TOPIC --location LOCATION \
--input-schema cloudeventschemav1_0
TOPIC_ID=$(az eventgrid topic show --resource-group RG --name TOPIC --query id -o tsv)
az role assignment create --assignee-object-id PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
--role "EventGrid Data Sender" --scope $TOPIC_IDCustom topics
Designing custom events
Well-designed events make subscriptions simple. The type names what happened in a stable, versionable form, such as Contoso.Documents.Indexed. The subject identifies what it happened to, as a path that subscribers can filter on by prefix or suffix, such as /tenants/contoso/documents/d-781. The data carries the facts consumers need, such as identifiers and counts, but not large payloads, which stay in their stores and are referenced.
Events describe facts in the past tense and should be safe to deliver more than once. Including an identifier that consumers can use for deduplication, the event id or a business key, makes idempotent handling straightforward.
Well-designed events
Publishing from Python
The azure-eventgrid library's EventGridPublisherClient publishes events to a topic. With a CloudEvents topic, events are CloudEvent objects; with an Event Grid schema topic, they are EventGridEvent objects. Several events can be sent in one call, up to 1 MB per request.
from azure.core.messaging import CloudEvent
from azure.eventgrid import EventGridPublisherClient
from azure.identity import DefaultAzureCredential
client = EventGridPublisherClient("https://TOPIC.REGION-1.eventgrid.azure.net/api/events",
DefaultAzureCredential())
client.send([
CloudEvent(source="/apps/indexer", type="Contoso.Documents.Indexed",
subject="/tenants/contoso/documents/d-781",
data={"documentId": "d-781", "chunks": 42}),
])Publishing returns once Event Grid has accepted the events; delivery to subscribers then happens asynchronously. A publish that fails with a transient error should be retried, which the SDK does automatically for common cases.
The following diagram shows how custom events flow from an indexing service through Event Grid to two consumers.

EventGridPublisherClient
Handlers and endpoint validation
The simplest handler is an Azure Function with an Event Grid trigger, which receives each event as an object and handles subscription validation automatically. A webhook handler, such as an API endpoint in App Service or Container Apps, must prove that it wants to receive events, so that Event Grid cannot be used to flood arbitrary URLs.
- For the Event Grid schema, Event Grid first sends a
Microsoft.EventGrid.SubscriptionValidationEventcontaining avalidationCode; the endpoint must echo it back asvalidationResponse, or an administrator can open thevalidationUrlmanually. - For CloudEvents, Event Grid sends an HTTP OPTIONS request with a
WebHook-Request-Originheader, and the endpoint must allow it in its response (abuse protection).
import azure.functions as func
app = func.FunctionApp()
@app.event_grid_trigger(arg_name="event")
def on_document_indexed(event: func.EventGridEvent):
data = event.get_json()
if already_handled(event.id): # at-least-once delivery: deduplicate
return
refresh_cache(data["documentId"])A handler should respond quickly with a success code and do slow work asynchronously, because Event Grid waits 30 seconds for a response before treating the attempt as failed. Handlers that need more time hand the event to a queue.
Validating a webhook
Publishing events securely
An indexing service running in Container Apps must notify other services whenever it finishes indexing a document. Consumers are a cache-invalidation function and an analytics webhook. The security team forbids shared keys and wants the analytics webhook to receive only events for the enterprise tenant.
The team creates a custom topic with the CloudEvents schema and disables local authentication. The indexing service's managed identity gets EventGrid Data Sender on the topic and publishes with EventGridPublisherClient and DefaultAzureCredential, using subjects such as /tenants/enterprise/documents/ID. The function subscribes with the Event Grid trigger; the webhook's subscription uses a subject begins with filter of /tenants/enterprise/, and the webhook answers the CloudEvents OPTIONS validation request.
Storing the topic access key in Key Vault would still use a shared key. Filtering inside the webhook would deliver every tenant's events to it first. A Service Bus queue would deliver each event to only one consumer.
Which role does an application's identity need to publish events to a custom topic with Microsoft Entra ID?
Show answer
EventGrid Data Sender on the topic.
Exam Tips
Remember for the exam
- Custom topics take a CloudEvents, Event Grid or custom input schema, set at creation.
- Publish with EventGridPublisherClient and DefaultAzureCredential; the identity needs EventGrid Data Sender.
- Webhooks must pass validation: echo the validationCode (Event Grid schema) or answer OPTIONS (CloudEvents).
- Design subjects as paths so subscribers can filter by prefix or suffix.