Create channel (v1)

Create a new Eventarc channel.

Code sample

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.Channel;
import com.google.cloud.eventarc.v1.ChannelName;
import com.google.cloud.eventarc.v1.EventarcClient;
import com.google.cloud.eventarc.v1.LocationName;
import java.util.concurrent.TimeUnit;

public class CreateChannel {

  public static void main(String[] args) throws Exception {
    String channelId = "example-channel-id";
    String projectId = "example-project-id";
    String locationId = "us-central1";
    createChannel(channelId, projectId, locationId);
  }

  public static void createChannel(String channelId, String projectId, String locationId)
      throws Exception {
    try (EventarcClient client = EventarcClient.create()) {
      String parent = LocationName.of(projectId, locationId).toString();
      Channel channel =
          Channel.newBuilder()
              .setName(ChannelName.of(projectId, locationId, channelId).toString())
              .build();

      Channel response =
          client.createChannelAsync(parent, channel, channelId).get(5, TimeUnit.MINUTES);
      System.out.println("Created channel: " + response.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();

/**
 * Creates an Eventarc channel.
 *
 * @param {string} channelId - ID of the channel (for example, 'example-channel-id')
 */
async function createChannel(channelId) {
  try {
    const projectId = await client.getProjectId();
    const parent = client.locationPath(projectId, 'us-central1');
    const channel = {
      name: client.channelPath(projectId, 'us-central1', channelId),
    };

    const [operation] = await client.createChannel({
      parent,
      channel,
      channelId,
    });

    const [response] = await operation.promise();
    console.log(`Created channel: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Channel already exists: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else {
      console.error(`Failed to create channel: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { createChannel };

Python

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

import os

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


def create_channel(channel_id: str) -> None:
    """Creates a channel in Google Cloud Eventarc.

    Args:
        channel_id: Identifier of the channel (for example, 'example-channel-id').
    """
    client = eventarc_v1.EventarcClient()

    project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project")
    location = "us-central1"
    parent = f"projects/{project_id}/locations/{location}"

    channel = eventarc_v1.Channel(
        name=f"{parent}/channels/{channel_id}",
    )

    try:
        operation = client.create_channel(
            parent=parent,
            channel=channel,
            channel_id=channel_id,
        )
        response = operation.result()
        print(f"Created channel: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create channel: {error}")

What's next

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