List message buses (v1)

List all message buses in a given project and location.

Code sample

Go

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	eventarc "cloud.google.com/go/eventarc/apiv1"
	eventarcpb "cloud.google.com/go/eventarc/apiv1/eventarcpb"
	"google.golang.org/api/iterator"
)

// listMessageBuses retrieves all message buses in the specified project and location.
func listMessageBuses(ctx context.Context, w io.Writer, projectID string, locationID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	client, err := eventarc.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create Eventarc client: %w", err)
	}
	defer client.Close()

	req := &eventarcpb.ListMessageBusesRequest{
		Parent: parent,
	}

	it := client.ListMessageBuses(ctx, req)
	for {
		bus, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("failed to iterate message buses: %w", err)
		}
		fmt.Fprintf(w, "Message bus: %s\n", bus.GetName())
	}

	return nil
}

Java

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.eventarc.v1.EventarcClient;
import com.google.cloud.eventarc.v1.LocationName;
import com.google.cloud.eventarc.v1.MessageBus;

public class ListMessageBuses {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    listMessageBuses(projectId, locationId);
  }

  public static void listMessageBuses(String projectId, String locationId) throws Exception {
    try (EventarcClient client = EventarcClient.create()) {
      String parent = LocationName.of(projectId, locationId).toString();
      for (MessageBus messageBus : client.listMessageBuses(parent).iterateAll()) {
        System.out.println("Message bus: " + messageBus.getName());
      }
    }
  }
}

Node.js

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {EventarcClient} = require('@google-cloud/eventarc');
const {status} = require('@grpc/grpc-js');

const client = new EventarcClient();

/**
 * Use the listMessageBuses method
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Google Cloud region (for example, 'us-central1') where the message buses reside.
 */
async function listMessageBuses(projectId, locationId) {
  try {
    const parent = client.locationPath(projectId, locationId);

    const [messageBuses] = await client.listMessageBuses({
      parent,
    });

    if (!messageBuses || messageBuses.length === 0) {
      console.log('No message buses found.');
      return;
    }

    for (const messageBus of messageBuses) {
      console.log(`Message bus: ${messageBus.name}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Parent resource not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      console.error(`Failed to list message buses: ${err.message}`);
    }
  }
}

module.exports = { listMessageBuses };

Python

To authenticate to Eventarc, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import eventarc_v1

client = eventarc_v1.EventarcClient()


def list_message_buses(project_id: str, location_id: str) -> None:
    """Lists Eventarc message buses in a location.

    Args:
        project_id: The Google Cloud project ID hosting the message buses.
        location_id: The Google Cloud location, for example 'us-central1' or 'global'.
    """
    parent = f"projects/{project_id}/locations/{location_id}"

    request = eventarc_v1.ListMessageBusesRequest(parent=parent)

    try:
        response = client.list_message_buses(request=request)
        for message_bus in response:
            print(f"Message bus: {message_bus.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Error listing message buses: {error}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.