Create Cloud PubSub Topic and Subscription via Python API

Jul 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_v1GOOGLE_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 googlefrom google.cloud import pubsub_v1GOOGLE_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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.