Publisher Guide

After you've set everything up and instantiated a Pubsub client, you can send requests to API. The general flow for a publisher application is as follows:

  1. Define a topic and send a request to the Pub/Sub system to create it.
  2. Create a message, and set data and optional attributes on it.
  3. Send a request to the Pub/Sub Server to publish the message to the desired topic.

The following code samples demonstrate how to send a few simple requests:

See Delete a topic for a discussion of what happens when you delete a topic. For a full list of methods, see the reference documentation.

Create a topic

Here is some sample code to create a topic:

Protocol

Request:

PUT https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic

Response:

200 OK
{
 "name": "projects/myproject/topics/mytopic"
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(_projectId, topicId);
try
{
    publisher.CreateTopic(topicName);
}
catch (RpcException e)
when (e.Status.StatusCode == StatusCode.AlreadyExists)
{
    // Already exists.  That's fine.
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

t, err := client.CreateTopic(ctx, topic)
if err != nil {
	return err
}
fmt.Printf("Topic created: %v\n", t)

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  // projectId <=  unique project identifier, eg. "my-project-id"
  // topicId <= "my-topic-id"
  TopicName topicName = TopicName.create(projectId, topicId);
  Topic topic = topicAdminClient.createTopic(topicName);
  return topic;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function createTopic (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // Creates a new topic, e.g. "my-new-topic"
  return pubsub.createTopic(topicName)
    .then((results) => {
      const topic = results[0];

      console.log(`Topic ${topic.name} created.`);

      return topic;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function create_topic($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->createTopic($topicName);

    printf('Topic created: %s' . PHP_EOL, $topic->name());
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def create_topic(topic_name):
    """Create a new Pub/Sub topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    topic.create()

    print('Topic {} created.'.format(topic.name))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"

topic = pubsub.create_topic "my-topic"

puts "Topic created #{topic.name}"

Publish messages to a topic

When using JSON, message data must be base64-encoded, and can be a maximum of 10MB after encoding. (The Java client libraries provide methods for Base64-encoding data.) Note that the message payload must not be empty; it must contain either a non-empty data field, or at least one attribute.

Also, though Pub/Sub usually delivers messages in order of publication, this is not guaranteed; it is possible for subscriptions to receive messages out of order. For this reason, we suggest that you include sequence information in the message payload or attribute so that subscribers that need in-order messaging can implement logic to do so.

Here is some sample code to publish a message to a topic:

Protocol

Request:

POST https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic:publish
{
  "messages": [
    {
      "attributes": {
        "key": "iana.org/language_tag",
        "value": "en"
      },
      "data": "SGVsbG8gQ2xvdWQgUHViL1N1YiEgSGVyZSBpcyBteSBtZXNzYWdlIQ=="
    }
  ]
}

Response:

200 OK
{
  "messageIds": [
    "19916711285"
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(_projectId, topicId);
PubsubMessage message = new PubsubMessage
{
    // The data is any arbitrary ByteString. Here, we're using text.
    Data = ByteString.CopyFromUtf8("Hello Cloud Pub/Sub!"),
    // The attributes provide metadata in a string-to-string 
    // dictionary.
    Attributes =
    {
        { "description", "Simple text message" }
    }
};
publisher.Publish(topicName, new[] { message });

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

t := client.Topic(topic)
result := t.Publish(ctx, &pubsub.Message{
	Data: []byte(msg),
})
// Block until the result is returned and a server-generated
// ID is returned for the published message.
id, err := result.Get(ctx)
if err != nil {
	return err
}
fmt.Printf("Published a message; msg ID: %v\n", id)

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = TopicName.create("my-project-id", "my-topic-id");
Publisher publisher = null;
List<ApiFuture<String>> messageIdFutures = new ArrayList<>();

try {
  // Create a publisher instance with default settings bound to the topic
  publisher = Publisher.defaultBuilder(topicName).build();

  List<String> messages = Arrays.asList("first message", "second message");

  // schedule publishing one message at a time : messages get automatically batched
  for (String message : messages) {
    ByteString data = ByteString.copyFromUtf8(message);
    PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();

    // Once published, returns a server-assigned message id (unique within the topic)
    ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
    messageIdFutures.add(messageIdFuture);
  }
} finally {
  // wait on any pending publish requests.
  List<String> messageIds = ApiFutures.allAsList(messageIdFutures).get();

  for (String messageId : messageIds) {
    System.out.println("published with message ID: " + messageId);
  }

  if (publisher != null) {
    // When finished with the publisher, shutdown to free up resources.
    publisher.shutdown();
  }
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function publishMessage (topicName, data) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  // Publishes the message, e.g. "Hello, world!" or { amount: 599.00, status: 'pending' }
  return topic.publish(data)
    .then((results) => {
      const messageIds = results[0];

      console.log(`Message ${messageIds[0]} published.`);

      return messageIds;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Publishes a message for a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $message  The message to publish.
 */
function publish_message($projectId, $topicName, $message)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $topic->publish(['data' => $message]);
    print('Message published' . PHP_EOL);
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def publish_message(topic_name, data):
    """Publishes a message to a Pub/Sub topic with the given data."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    # Data must be a bytestring
    data = data.encode('utf-8')

    message_id = topic.publish(data)

    print('Message {} published.'.format(message_id))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

topic.publish "A Message"

List topics in your project

By default, a maximum of 100 results are returned per query; you can specify an alternate value up to 1,000 in the pageSize query parameter.

Here is some sample code to get a list of topics defined for your project:

Protocol

Request:

GET https://pubsub.googleapis.com/v1/projects/myproject/topics

Response:

200 OK
{
  "topics": [
    {
      "name": "projects/myproject/topics/mytopic1"
    },
    {
      "name": "projects/myproject/topics/mytopic2"
    }
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

ProjectName projectName = new ProjectName(_projectId);
IEnumerable<Topic> topics = publisher.ListTopics(projectName);

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

var topics []*pubsub.Topic

it := client.Topics(ctx)
for {
	topic, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	topics = append(topics, topic)
}

return topics, nil

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  ListTopicsRequest listTopicsRequest =
      ListTopicsRequest.newBuilder()
          .setProjectWithProjectName(ProjectName.create(projectId))
          .build();
  ListTopicsPagedResponse response = topicAdminClient.listTopics(listTopicsRequest);
  Iterable<Topic> topics = response.iterateAll();
  for (Topic topic : topics) {
    // do something with the topic
  }
  return response;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function listTopics () {
  // Instantiates a client
  const pubsub = PubSub();

  // Lists all topics in the current project
  return pubsub.getTopics()
    .then((results) => {
      const topics = results[0];

      console.log('Topics:');
      topics.forEach((topic) => console.log(topic.name));

      return topics;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Lists all Pub/Sub topics.
 *
 * @param string $projectId  The Google project ID.
 */
function list_topics($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    foreach ($pubsub->topics() as $topic) {
        printf('Topic: %s' . PHP_EOL, $topic->name());
    }
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def list_topics():
    """Lists all Pub/Sub topics in the current project."""
    pubsub_client = pubsub.Client()

    for topic in pubsub_client.list_topics():
        print(topic.name)

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topics = pubsub.topics

puts "Topics:"
topics.each do |topic|
  puts topic.name
end

Delete a topic

When you delete a topic, its subscriptions are not deleted, and the subscriptions' backlog is available. After a topic is deleted, its subscriptions have the topic name _deleted-topic_.

Here is some sample code to delete a topic:

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(_projectId, topicId);
publisher.DeleteTopic(topicName);

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

t := client.Topic(topic)
if err := t.Delete(ctx); err != nil {
	return err
}
fmt.Printf("Deleted topic: %v\n", t)

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  TopicName topicName = TopicName.create(projectId, topicId);
  topicAdminClient.deleteTopic(topicName);
  return topicName;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function deleteTopic (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  // Deletes the topic
  return topic.delete()
    .then(() => {
      console.log(`Topic ${topic.name} deleted.`);
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function delete_topic($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $topic->delete();

    printf('Topic deleted: %s' . PHP_EOL, $topic->name());
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def delete_topic(topic_name):
    """Deletes an existing Pub/Sub topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    topic.delete()

    print('Topic {} deleted.'.format(topic.name))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

topic.delete

puts "Deleted topic my-topic"

Send feedback about...

Cloud Pub/Sub