Azure Functions Documentation

Azure Functions Event Hubs Bindings

Azure Functions provides powerful triggers and bindings for interacting with Azure Event Hubs, a highly scalable data streaming platform and event ingestion service. These bindings simplify the process of reading events from or writing events to Event Hubs within your serverless functions.

Key Benefits:
  • Simplifies event ingestion and processing.
  • Reduces boilerplate code for Event Hubs integration.
  • Enables event-driven architectures with Azure Functions.

Event Hubs Trigger

The Event Hubs trigger allows your function to be executed automatically when new events are available in an Event Hub. It handles the complex task of managing checkpoints and leasing to ensure reliable event processing.

Configuration

The Event Hubs trigger is configured in your function.json file. You'll need to specify the eventHubName, connection string setting name, and optionally the consumerGroup.


{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "myEventHubTrigger",
      "direction": "in",
      "eventHubName": "myeventhub",
      "connection": "EventHubConnectionString",
      "consumerGroup": "$Default"
    }
  ]
}
                    

Code Example (Python)

Your function code will receive the event data as a parameter.


import logging
import azure.functions as func

def main(myEventHubTrigger: func.EventHubData):
    logging.info('Python Event Hub trigger function processed a record')
    for event in myEventHubTrigger.get_body().decode('utf-8').split('\n'):
        logging.info(f'EnqueuedTimeUtc = {event.enqueued_time_utc}')
        logging.info(f'PartitionKey = {event.partition_key}')
        logging.info(f'SequenceNumber = {event.sequence_number}')
        logging.info(f'Body = {event.body}')
                    

Event Hubs Output Binding

The Event Hubs output binding allows your function to send data to an Event Hub. This is useful for scenarios like aggregating data, transforming events, or publishing results.

Configuration

The Event Hubs output binding is also configured in function.json.


{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "eventHub",
      "name": "outputEventHub",
      "direction": "out",
      "eventHubName": "outputeventhub",
      "connection": "EventHubConnectionString"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}
                    

Code Example (Python)

Your function will return a value or modify a parameter decorated as an output binding.


import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, outputEventHub: func.Out[str]) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        message = f"Hello, {name}! This HTTP triggered function executed successfully. Sending a message to Event Hubs."
        logging.info(f"Sending message to Event Hubs: {message}")
        outputEventHub.set(json.dumps({"message": message, "processed_by": "http_function"}))
        return func.HttpResponse(
             message,
             status_code=200
        )
    else:
        return func.HttpResponse(
             "Please pass a name on the query string or in the request body",
             status_code=400
        )
                    

Advanced Scenarios

For more complex scenarios, consider:

  • Using the Event Hubs SDK directly for fine-grained control.
  • Implementing batch processing for higher throughput.
  • Handling poison messages and retries.

API Reference

Event Hubs Trigger Parameters

Parameter Description Required
type Must be eventHubTrigger. Yes
name The name of the parameter in your function code that receives the Event Hub data. Yes
direction Must be in. Yes
eventHubName The name of the Event Hub to monitor. Yes
connection The name of an application setting that contains the Event Hub connection string. Yes
consumerGroup The consumer group for the Event Hub. Defaults to $Default. No

Event Hubs Output Binding Parameters

Parameter Description Required
type Must be eventHub. Yes
name The name of the parameter in your function code that represents the output binding. Yes
direction Must be out. Yes
eventHubName The name of the target Event Hub. Yes
connection The name of an application setting that contains the Event Hub connection string. Yes

Learn More