Skip to content

Example of using PublisherClient's create_topic method cause TypeError #349

@OlafMeuwese

Description

@OlafMeuwese

The examples (here) show the create_topic like:

import os
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic_name = 'projects/{project_id}/topics/{topic}'.format(
    project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
    topic='MY_TOPIC_NAME',  # Set this to something appropriate.
)
publisher.create_topic(topic_name) # this is the problem

However, if you run this, you get

Stack trace

/lib/python3.8/site-packages/proto/message.py in __init__(self, mapping, ignore_unknown_fields, **kwargs)
    484         else:
    485             # Sanity check: Did we get something not a map? Error if so.
--> 486             raise TypeError(
    487                 "Invalid constructor input for %s: %r"
    488                 % (self.__class__.__name__, mapping,)

TypeError: Invalid constructor input for Topic: 'projects/<project_id>/topics/MY_TOPIC_NAME'

Possible solution

import os
from google.cloud import pubsub_v1

publisher = pubsub_v1.PublisherClient()
topic_name = 'projects/{project_id}/topics/{topic}'.format(
    project_id=os.getenv('GOOGLE_CLOUD_PROJECT'),
    topic='MY_TOPIC_NAME',  # Set this to something appropriate.
)
publisher.create_topic({"name": topic_name})

or

publisher.create_topic(name=topic_name)

Environment details

  • OS type and version: MacOs Big Sur (11.2.3)
  • Python version: 3.8.5
  • pip version: 21.0.1
  • google-cloud-pubsub version: 2.3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    api: pubsubIssues related to the googleapis/python-pubsub API.priority: p2Moderately-important priority. Fix may not be included in next release.samplesIssues that are directly related to samples.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions