Create Google API source (v1)

Create a new Google API source in Eventarc.

Code sample

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
import google.auth
import google.auth.exceptions
from google.cloud import eventarc_v1


def create_google_api_source(google_api_source_id: str) -> None:
    """Creates a Google API source in Eventarc.

    Args:
        google_api_source_id: ID of the Google API source (for example, 'example-googleapisource-id').
    """
    client = eventarc_v1.EventarcClient()

    project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
    if not project_id:
        try:
            _, project_id = google.auth.default()
        except google.auth.exceptions.DefaultCredentialsError:
            project_id = "example-project-id"
    project_id = project_id or "example-project-id"

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

    message_bus = os.environ.get("EVENTARC_MESSAGE_BUS", "example-message-bus")
    destination = os.environ.get(
        "EVENTARC_DESTINATION", f"{parent}/messageBuses/{message_bus}"
    )

    google_api_source = eventarc_v1.GoogleApiSource(
        destination=destination,
    )

    try:
        operation = client.create_google_api_source(
            parent=parent,
            google_api_source=google_api_source,
            google_api_source_id=google_api_source_id,
        )
        response = operation.result()
        print(f"Created Google API source: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create Google API source: {error}")

What's next

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