Create Cloud PubSub Topic and Subscription via Python API

July 31, 2019

NOTE: If you don’t need to create topic and subscription programatically, you can Create Topic or Subscription via Cloud Console or gcloud.

Install python libraries.

pip install --upgrade google-cloud-pubsub

Create Topic

from google.cloud import pubsub_v1

GOOGLE_PROJECT_ID = ...
TOPIC = ...

publisher = pubsub_v1.PublisherClient()
# topic_path = f"projects/{GOOGLE_PROJECT_ID}/topics/{TOPIC}"
topic_path = publisher.topic_path(GOOGLE_PROJECT_ID, TOPIC)

publisher.create_topic(topic_path)

Create Subscription

import google
from google.cloud import pubsub_v1

GOOGLE_PROJECT_ID = ...
TOPIC = ...
SUB = ...

subscriber = pubsub_v1.SubscriberClient()
# subscription_path = f"projects/{GOOGLE_PROJECT_ID}/subscriptions/{SUB}"
subscription_path = subscriber.subscription_path(GOOGLE_PROJECT_ID, SUB)
# topic_path = f"projects/{GOOGLE_PROJECT_ID}/topics/{TOPIC}"
topic_path = subscriber.topic_path(GOOGLE_PROJECT_ID, TOPIC)

try:
    subscriber.create_subscription(name=subscription_path, topic=topic_path)
except google.api_core.exceptions.AlreadyExists:
    print(f"{subscription_path} already exist")

NOTE: Publish and subscribe messages via Python.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.