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 import pubsub_v1

TOPIC = ...

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


Create Subscription

import google
from import pubsub_v1

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)

    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.


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