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: