# eb-event-bus

Part of **EB**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Create and manage event buses](../../intent/eb-create-bus/SKILL.md). If you're unsure which path to take, check the routing skill first.

# EventBridge Event Bus Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Create Event Bus | Synchronous | Creates an event bus in Alibaba Cloud EventBridge. This API allows users to define and configure event buses for routing events across services. |
| Delete Event Bus | Synchronous | Deletes an event bus in Alibaba Cloud EventBridge. This API allows users to remove a specified event bus by providing its name. |
| Get Event Bus Details | Synchronous | Queries the detailed information about an event bus in Alibaba Cloud EventBridge, including its ARN, name, description, and creation timestamp. |
| List Event Buses | Synchronous | Queries all event buses in the specified region. This API supports filtering by name prefix and implements pagination using Limit and NextToken parameters. |
| Update Event Bus | Synchronous | Updates an event bus in the EventBridge service. This API allows users to modify the description of an existing event bus by providing its name. |
| Subscribe to Domain Name Events | Synchronous | Describes the event types published by Domain Names to EventBridge through ActionTrail, including management events, API calls, console operations, and logon/sign-out events. |
| Publish Kafka Events | Synchronous | Describes the event types published by Message Queue for Apache Kafka to EventBridge through ActionTrail, including operations performed by Alibaba Cloud, API calls, console actions, and login/logout events. |
| Publish PCDN Events | Synchronous | Describes the types of P2P CDN (PCDN) events that ActionTrail records and can be published to EventBridge. |

## API Calling Patterns

### Authentication
The primary authentication method is **AccessKey-based signature authentication**.

- Use the header format: `Authorization: acs <AccessKeyId>:<Signature>`
- Set credentials via environment variables:
  - `ALIBABA_CLOUD_ACCESS_KEY_ID`
  - `ALIBABA_CLOUD_ACCESS_KEY_SECRET`

While bearer token authentication appears in some examples (`Authorization: Bearer $DASHSCOPE_API_KEY`), the standard and recommended approach for EventBridge APIs is AccessKey signature authentication.

### Service Endpoint
EventBridge APIs use region-specific endpoints with this pattern:

```text
https://{accountId}.eventbridge.{regionId}.aliyuncs.com
```

Common regions include:
- `cn-hangzhou`
- `cn-shanghai`
- `cn-beijing`

For international accounts, you may also use:
- `https://api.alibabacloud.com/api/eventbridge/2020-04-01/{Action}`

### Synchronous API Pattern
All Event Bus Management APIs follow a synchronous request-response pattern:

1. Construct an HTTP POST request to the appropriate endpoint
2. Include required headers:
   - `Host`: `{accountId}.eventbridge.{regionId}.aliyuncs.com`
   - `Date`: Current date in RFC 1123 format
   - `x-eventbridge-version`: `2020-04-01`
   - `Authorization`: `acs <AccessKeyId>:<Signature>`
   - `Content-Type`: `application/json;charset=UTF-8`
3. Send the request body as JSON containing the required parameters
4. Receive an immediate JSON response with success/failure status

No polling or streaming is required — responses are returned directly.

## Parameter Reference

### Create Event Bus

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| EventBusName | string | true | - | - | The name of the event bus. |
| Description | string | false | - | - | The description of the event bus. |

### Delete Event Bus

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| EventBusName | string | true | - | - | The name of the event bus to be deleted. |

### Get Event Bus Details

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| EventBusName | string | true | - | - | The name of the event bus to query. |

### List Event Buses

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| NamePrefix | string | false | - | - | The prefix of the names of the event buses that you want to query. |
| Limit | integer | false | 10 | max 100 | The maximum number of entries to return in a request. |
| NextToken | string | false | - | - | Used for pagination when results exceed the limit. |

### Update Event Bus

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| EventBusName | string | true | - | - | The name of the event bus. |
| Description | string | false | - | - | The description. |

### Publish PCDN Events

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| type | string | true | - | One of: pcdn:ActionTrail:AliyunServiceEvent, pcdn:ActionTrail:ApiCall, pcdn:ActionTrail:ConsoleOperation, pcdn:ActionTrail:ConsoleSignin, pcdn:ActionTrail:ConsoleSignout | The type of PCDN event to be published. |

## Code Examples

### Create Event Bus - Python - All Regions

```python
# -*- coding: utf-8 -*-

from alibabacloud_eventbridge.client import Client as EventBridgeClient
from alibabacloud_event_bridge import models as event_bridge_models
from alibabacloud_tea_console.client import Client as ConsoleClient
from alibabacloud_tea_util.client import Client as UtilClient

class create_event_bus_sample(object):
    def __init__(self):
        pass

    @staticmethod
    def create_client():
        """
        Uses the create_client() function to initialize common request parameters.
        """
        config = event_bridge_models.Config(

        )
        # Your AccessKey ID.
        config.access_key_id = "<accessKeyId>"
        # Your AccessKey secret.
        config.access_key_secret = "<accessKeySecret>"
        # Your endpoint.
        config.endpoint = "<endpoint>"
        return EventBridgeClient(config)

    @staticmethod
    def create_event_bus_sample(client):
        try:
            create_event_bus_request = event_bridge_models.CreateEventBusRequest(

            )
            create_event_bus_request.event_bus_name = "demo-bus"
            response = client.create_event_bus(create_event_bus_request)
            ConsoleClient.log("--------------------Create bus success --------------------")
            ConsoleClient.log(UtilClient.to_jsonstring(response.to_map()))
        except Exception as error:
            ConsoleClient.log(error.message)

    @staticmethod
    def main(args):
        client = create_event_bus_sample.create_client()
        create_event_bus_sample.create_event_bus_sample(client)

create_event_bus_sample.main("")
```

### Delete Event Bus - Java - All Regions

```java
import com.aliyun.eventbridge.EventBridge;
import com.aliyun.eventbridge.EventBridgeClient;
import com.aliyun.eventbridge.models.Config;
import com.aliyun.eventbridge.models.DeleteEventBusRequest;

public class deleteEventBusSample {

    private EventBridge eventBridgeClient;

    public deleteEventBusSample()  {
        Config authConfig = new Config();
        authConfig.accessKeyId = "{accessKeyId}";
        authConfig.accessKeySecret = "{accessKeySecret}";
        authConfig.endpoint = "{endpoint}";
        eventBridgeClient = new EventBridgeClient(authConfig);
    }

    public void deleteEventBusSample() {
        try {
            DeleteEventBusRequest deleteEventBusRequest = new DeleteEventBusRequest();
            deleteEventBusRequest.setEventBusName("mybus");
            eventBridgeClient.deleteEventBus(deleteEventBusRequest);
            System.out.println("delete bus success : " + deleteEventBusRequest.getEventBusName());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)  {
        deleteEventBusSample sample = new deleteEventBusSample();
        try {
            sample.deleteEventBusSample();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
```

### List Event Buses - Bash - China

```bash
POST /openapi/listEventBuses HTTP/1.1
Host: 123456789098****.eventbridge.cn-hangzhou.aliyuncs.com
Date: Sat, 18 Apr 2020 05:30:41 GMT
x-eventbridge-version: 2020-04-01
Authorization: acs vZ3VL0SuJdHi****:Jo2PbTj******zYAYoYslKLvWzg=
Content-Type: application/json;charset=UTF-8
Content-Length: 26

{
    "NamePrefix": "My",
    "Limit": 10,
    "NextToken": "10"
}
```

### Get Event Bus Details - C# - All Regions

```csharp
using System;
using System.Collections.Generic;

using Tea;

namespace Alibabacloud.Sample
{
    public class Client
    {

        /**
         * Uses the CreateClient() function to initialize common request parameters.
         */
        public static AlibabaCloud.SDK.EventBridge.EventBridgeClient CreateClient()
        {
            AlibabaCloud.SDK.EventBridge.Models.Config config = new AlibabaCloud.SDK.EventBridge.Models.Config();
            // Your AccessKey ID.
            config.AccessKeyId = "<accessKeyId>";
            // Your AccessKey secret.
            config.AccessKeySecret = "<accessKeySecret>";
            // Your endpoint.
            config.Endpoint = "<endpoint>";
            return new AlibabaCloud.SDK.EventBridge.EventBridgeClient(config);
        }

        public static void GetEventBusSample(AlibabaCloud.SDK.EventBridge.EventBridgeClient client)
        {
            try
            {
                AlibabaCloud.SDK.EventBridge.Models.GetEventBusRequest describeEventBusRequest = new AlibabaCloud.SDK.EventBridge.Models.GetEventBusRequest();
                describeEventBusRequest.EventBusName = "demo-bus";
                AlibabaCloud.SDK.EventBridge.Models.GetEventBusResponse deScribeResponse = client.GetEventBus(describeEventBusRequest);
                Console.WriteLine("--------------------get bus success --------------------");
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(deScribeResponse.ToMap()));
            }
            catch (TeaException error)
            {
                Console.WriteLine(error.Message);
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
                { { "message", _error.Message }
                });
                Console.WriteLine(error.Message);
            }
        }

        static void Main(string[] args)
        {
            AlibabaCloud.SDK.EventBridge.EventBridgeClient client = CreateClient();
            GetEventBusSample(client);
            Console.ReadKey();
        }

    }
}
```

### Update Event Bus - JSON Response - All Regions

```json
{
  "Message": "The event bus [xxxx] not existed!",
  "RequestId": "f2099962-1628-45f1-9782-2bf6daad823f",
  "Code": "Success",
  "Success": true
}
```

### List Event Buses with Pagination - Go - All Regions

```go
package main
import (
	"fmt"
	"github.com/alibabacloud-go/eventbridge-sdk/eventbridge"
	console "github.com/alibabacloud-go/tea-console/client"
	"github.com/alibabacloud-go/tea/tea"
)

/**
* Use the CreateClient() function to initialize common request parameters. 
 */
func CreateClient() (_result *eventbridge.Client, _err error) {
	config := &eventbridge.Config{}
	// Your AccessKey ID. 
	config.AccessKeyId = tea.String("<accessKeyId>")
	// Your AccessKey secret. 
	config.AccessKeySecret = tea.String("<accessKeySecret>")
	// Your endpoint. 
	config.Endpoint = tea.String("<endpoint>")
	_result = &eventbridge.Client{}
	_result, _err = eventbridge.NewClient(config)
	return _result, _err
}

func ListEventBusesSample(client *eventbridge.Client) (_err error) {
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		listEventBusesRequest := &eventbridge.ListEventBusesRequest{}
		resp, _err := client.ListEventBuses(listEventBusesRequest)
		if _err != nil {
			return _err
		}
		fmt.Println(resp)
		console.Log(tea.String("--------------------list buses success--------------------"))

		return nil
	}()

	_err = tryErr
	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.SetErrMsg(tryErr.Error())
		}
		console.Log(error.Message)
	}
	return _err
}

func main() {
	client, _err := CreateClient()
	if _err != nil {
		panic(_err)
	}

	_err = ListEventBusesSample(client)
	if _err != nil {
		panic(_err)
	}
}
```

## Response Format

```json
{
  "Message": "The event bus [xxxx] not existed!",
  "RequestId": "A995F07C-E503-5881-9962-9CECA8566876",
  "Data": {
    "EventBusARN": "acs:eventbridge:cn-hangzhou:123456789098****:eventbus/MyEventBus"
  },
  "Code": "Success",
  "Success": true
}
```

**Key Fields**:
- `Data.EventBusARN` — The Alibaba Cloud Resource Name (ARN) of the created event bus
- `RequestId` — Unique identifier for the API request, useful for troubleshooting
- `Code` — Status code indicating success or specific error type
- `Success` — Boolean indicating whether the request succeeded

## Error Handling

| Error Code | Description | Recommended Action |
|------------|-------------|-------------------|
| 400 | Bad Request - The request is malformed or missing required parameters. | Verify that all required parameters are included and properly formatted. |
| 401 | Unauthorized. The AccessKey ID or AccessKey secret is incorrect or not authorized. | Check your AccessKey credentials and ensure they have the necessary permissions. |
| 403 | Service not enable. The service is not enabled in the account. | Enable the EventBridge service in the Alibaba Cloud console or via API before making requests. |
| 404 | Not found. The specified event bus does not exist. | Verify the event bus name exists in the specified region. |
| 429 | Too Many Requests - The rate limit for creating event buses has been exceeded. | Implement exponential backoff and retry logic with delays between requests. |
| 500 | Internal Server Error - An unexpected error occurred on the server side. | Retry the request after a short delay; if persistent, contact support with the RequestId. |

### Rate Limits & Retry
- **QPS Limit**: 100 queries per second per account
- **Daily Limit**: Up to 1000 delete operations per day per account
- **Retry Strategy**: For 429 errors, implement exponential backoff starting with 1-second delays
- **Free Tier**: Most operations include 1000 free calls per month

## Environment Requirements

**SDK Requirements**:
- Python: `alibabacloud_eventbridge` package
- Java: `com.aliyun.eventbridge:1.0.0` or higher
- Go: `github.com/alibabacloud-go/eventbridge-sdk/eventbridge >= 1.0.0`
- PHP: `AlibabaCloud/SDK:EventBridge>=1.0.0`
- C#: `AlibabaCloud.SDK.EventBridge` package
- TypeScript: `@alicloud/eventbridge` package

**Environment Variables**:
```bash
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
```

## FAQ

Q: How do I authenticate my EventBridge API requests?
A: Use AccessKey-based signature authentication with the `Authorization: acs <AccessKeyId>:<Signature>` header. Set your credentials via environment variables `ALIBABA_CLOUD_ACCESS_KEY_ID` and `ALIBABA_CLOUD_ACCESS_KEY_SECRET`.

Q: What regions are supported for EventBridge event buses?
A: EventBridge supports all major Alibaba Cloud regions including cn-hangzhou, cn-shanghai, cn-beijing, and others. Use the endpoint pattern `https://{accountId}.eventbridge.{regionId}.aliyuncs.com`.

Q: Can I delete an event bus that has active rules or connections?
A: No, you must first delete all associated rules and connections before deleting an event bus. Attempting to delete a bus with dependencies will result in an error.

Q: How do I handle pagination when listing many event buses?
A: Use the `Limit` parameter (max 100) and `NextToken` from the response to implement pagination. Continue making requests with the returned `NextToken` until all results are retrieved.

Q: Are failed API requests charged?
A: For most operations like GetEventBus and ListEventBuses, only successful requests are charged. However, CreateEventBus charges for all requests regardless of success. Check the specific billing notes for each operation.

## Pricing & Billing

### Billing Model
All Event Bus Management APIs use a **per-request** billing model.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| standard | 0.0001 / | 0.0001 / |
| default | 0.001 / | 0.001 / |

### Free Tier
Monthly free quotas are available:
- 1000 free calls per month for most operations
- 100 free calls per month for some operations
- Free tier resets monthly

### Usage Limits
- 100 QPS per account for most operations
- Single request can return maximum 100 event buses
- Up to 1000 delete operations per day per account
- Maximum 100 event buses per account

### Billing Notes
- CreateEventBus charges for all requests, including failed ones
- DeleteEventBus only charges for successful operations
- GetEventBus and ListEventBuses charge per successful API call
- Free tier usage is tracked separately for each operation type