Managing Topics and Subscriptions

This document gives an overview of how to manage topics and subscriptions in Cloud Pub/Sub.

Managing Topics

You can create, delete, and view topics using the API, the GCP Console, or the gcloud command-line tool. See the gcloud pubsub reference for a complete list of Cloud Pub/Sub API gcloud commands.

For an introduction to the GCP Console, see the GCP Console Quickstart.

Create a topic

You must first create a topic before you can publish or subscribe to it. Here is an example showing how to create a topic:

Protocol

Request:

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

Response:

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

GCLOUD COMMAND

  gcloud pubsub topics create myTopic

C#

Before trying this sample, follow the C# setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub C# API reference documentation .

            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();

            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

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

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

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

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

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';

// Creates a new topic
pubsub
  .createTopic(topicName)
  .then(results => {
    const topic = results[0];
    console.log(`Topic ${topicName} created.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

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

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)

topic = publisher.create_topic(topic_path)

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

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic  = pubsub.create_topic topic_name

puts "Topic #{topic.name} created."

Delete a topic

Here is an example showing how to delete a topic:

Protocol

Request:

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

Response:

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

GCLOUD COMMAND

  gcloud pubsub topics delete myTopic

C#

Before trying this sample, follow the C# setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub C# API reference documentation .

PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
TopicName topicName = new TopicName(projectId, topicId);
publisher.DeleteTopic(topicName);
Console.WriteLine("Topic deleted.");

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

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

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

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

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';

// Deletes the topic
pubsub
  .topic(topicName)
  .delete()
  .then(() => {
    console.log(`Topic ${topicName} deleted.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

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

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)

publisher.delete_topic(topic_path)

print('Topic deleted: {}'.format(topic_path))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic = pubsub.topic topic_name
topic.delete

puts "Topic #{topic_name} deleted."

When you delete a topic, its subscriptions are not deleted, and the subscription's message backlog is available for subscribers. After a topic is deleted, its subscriptions have the topic name _deleted-topic_. If you try to create a topic with the same name as a topic you had just deleted, expect an error for a brief period of time after the deletion.

List topics

Here is an example showing how to get a list of topics:

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"
    }
  ]
}

GCLOUD COMMAND

   gcloud pubsub topics list

C#

Before trying this sample, follow the C# setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub C# API reference documentation .

ProjectName projectName = new ProjectName(projectId);
IEnumerable<Topic> topics = publisher.ListTopics(projectName);
foreach (Topic topic in topics)
{
    Console.WriteLine($"{topic.Name}");
}

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

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

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  ListTopicsRequest listTopicsRequest =
      ListTopicsRequest.newBuilder()
          .setProject(ProjectName.format(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

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

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

    console.log('Topics:');
    topics.forEach(topic => console.log(topic.name));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

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

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"

publisher = pubsub_v1.PublisherClient()
project_path = publisher.project_path(project_id)

for topic in publisher.list_topics(project_path):
    print(topic)

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id = "Your Google Cloud Project ID"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topics = pubsub.topics

puts "Topics in project:"
topics.each do |topic|
  puts topic.name
end
By default, a maximum of 100 results are returned per query. You can specify an alternative value up to 1,000 using the page size parameter.

Managing Subscriptions

This section covers how to create and manage push, pull subscriptions. For an overview and comparison of pull and push subscriptions, see the Subscriber Overview.

Create a Pull Subscription

You must create a subscription to a topic before subscribers can receive messages published to the topic. You can create a subscription using the Google Cloud Platform Console UI or the gcloud command-line tool, as described in the gcloud Quickstart. Also see the gcloud reference for subscriber commands.

Protocol

Request:

PUT https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription
{
  "topic": "projects/someproject/topics/sometopic"
  // Only needed if you are using push delivery
  "pushConfig": {
    "pushEndpoint": "https://myproject.appspot.com/myhandler"
  }
}

Response:

200 OK
{
  "name": "projects/myproject/subscriptions/mysubscription",
  "topic": "projects/someproject/topics/sometopic",
  "pushConfig": {
    "pushEndpoint": "https://myproject.appspot.com/myhandler"
  },
  "ackDeadlineSeconds": 10
}

GCLOUD COMMAND

   gcloud pubsub subscriptions create mySubscription --topic myTopic

C#

Before trying this sample, follow the C# setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub C# API reference documentation .

SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
TopicName topicName = new TopicName(projectId, topicId);
SubscriptionName subscriptionName = new SubscriptionName(projectId,
    subscriptionId);
try
{
    Subscription subscription = subscriber.CreateSubscription(
        subscriptionName, topicName, pushConfig: null,
        ackDeadlineSeconds: 60);
}
catch (RpcException e)
when (e.Status.StatusCode == StatusCode.AlreadyExists)
{
    // Already exists.  That's fine.
}

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

sub, err := client.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{
	Topic:       topic,
	AckDeadline: 20 * time.Second,
})
if err != nil {
	return err
}
fmt.Printf("Created subscription: %v\n", sub)

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  // eg. projectId = "my-test-project", topicId = "my-test-topic"
  ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
  // eg. subscriptionId = "my-test-subscription"
  ProjectSubscriptionName subscriptionName =
      ProjectSubscriptionName.of(projectId, subscriptionId);
  // create a pull subscription with default acknowledgement deadline
  Subscription subscription =
      subscriptionAdminClient.createSubscription(
          subscriptionName, topicName, PushConfig.getDefaultInstance(), 0);
  return subscription;
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following lines to run the sample.
 */
// const topicName = 'my-topic';
// const subscriptionName = 'my-sub';

// Creates a new subscription
pubsub
  .topic(topicName)
  .createSubscription(subscriptionName)
  .then(results => {
    const subscription = results[0];
    console.log(`Subscription ${subscriptionName} created.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

use Google\Cloud\PubSub\PubSubClient;

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

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

Python

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"
# TODO subscription_name = "Your Pub/Sub subscription name"

subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project_id, topic_name)
subscription_path = subscriber.subscription_path(
    project_id, subscription_name)

subscription = subscriber.create_subscription(
    subscription_path, topic_path)

print('Subscription created: {}'.format(subscription))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id        = "Your Google Cloud Project ID"
# topic_name        = "Your Pubsub topic name"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic        = pubsub.topic topic_name
subscription = topic.subscribe subscription_name

puts "Pull subscription #{subscription_name} created."

Create a Push Subscription

You can create push subscriptions by providing an HTTP endpoint URL, as shown in these examples:

GCLOUD COMMAND

   gcloud pubsub subscriptions create mySubscription --topic myTopic --push-endpoint="https://myapp.appspot.com/push"

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

// For example, endpoint is "https://my-test-project.appspot.com/push".
sub, err := client.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{
	Topic:       topic,
	AckDeadline: 10 * time.Second,
	PushConfig:  pubsub.PushConfig{Endpoint: endpoint},
})
if err != nil {
	return err
}
fmt.Printf("Created subscription: %v\n", sub)

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
  ProjectSubscriptionName subscriptionName =
      ProjectSubscriptionName.of(projectId, subscriptionId);

  // eg. endpoint = "https://my-test-project.appspot.com/push"
  PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build();

  // acknowledgement deadline in seconds for the message received over the push endpoint
  int ackDeadlineInSeconds = 10;

  Subscription subscription =
          subscriptionAdminClient.createSubscription(
                  subscriptionName, topicName, pushConfig, ackDeadlineInSeconds);
  return subscription;
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following lines to run the sample.
 */
// const topicName = 'my-topic';
// const subscriptionName = 'my-sub';

const options = {
  pushConfig: {
    // Set to an HTTPS endpoint of your choice. If necessary, register
    // (authorize) the domain on which the server is hosted.
    pushEndpoint: `https://${pubsub.projectId}.appspot.com/push`,
  },
};

pubsub
  .topic(topicName)
  .createSubscription(subscriptionName, options)
  .then(results => {
    const subscription = results[0];

    console.log(`Subscription ${subscriptionName} created.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub push subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 * @param string $endpoint  The endpoint for the push subscription.
 */
function create_push_subscription($projectId, $topicName, $subscriptionName, $endpoint)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $subscription = $topic->subscription($subscriptionName);
    $subscription->create([
        'endpoint' => $endpoint
    ]);

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

Python

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"
# TODO subscription_name = "Your Pub/Sub subscription name"
# TODO endpoint = "https://my-test-project.appspot.com/push"

subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project_id, topic_name)
subscription_path = subscriber.subscription_path(
    project_id, subscription_name)

push_config = pubsub_v1.types.PushConfig(
    push_endpoint=endpoint)

subscription = subscriber.create_subscription(
    subscription_path, topic_path, push_config)

print('Push subscription created: {}'.format(subscription))
print('Endpoint for subscription is: {}'.format(endpoint))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id        = "Your Google Cloud Project ID"
# topic_name        = "Your Pubsub topic name"
# subscription_name = "Your Pubsub subscription name"
# endpoint          = "Endpoint where your app receives messages"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic        = pubsub.topic topic_name
subscription = topic.subscribe subscription_name,
  endpoint: endpoint

puts "Push subscription #{subscription_name} created."

Update a subscription

Once a subscription has been created, you can update the push endpoint of a subscription or switch from push to pull and vice versa. Here are examples showing how to update an existing pull or push subscription by specifying a non-empty, valid HTTPS push endpoint URL:

GCLOUD COMMAND

   gcloud pubsub subscriptions modify-push-config mySubscription --push-endpoint="https://anotherapp.appspot.com/push"

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

// For example, endpoint is "https://my-test-project.appspot.com/push".
subConfig, err := client.Subscription(subName).Update(ctx, pubsub.SubscriptionConfigToUpdate{
	PushConfig: &pubsub.PushConfig{Endpoint: endpoint},
})
if err != nil {
	return err
}
fmt.Printf("Updated subscription config: %#v", subConfig)

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId);
  PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build();
  subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';
// const subscriptionName = 'my-sub';

const options = {
  // Set to an HTTPS endpoint of your choice. If necessary, register
  // (authorize) the domain on which the server is hosted.
  pushEndpoint: `https://${pubsub.projectId}.appspot.com/push`,
};

pubsub
  .topic(topicName)
  .subscription(subscriptionName)
  .modifyPushConfig(options)
  .then(() => {
    console.log(`Modified push config for subscription ${subscriptionName}.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"
# TODO subscription_name = "Your Pub/Sub subscription name"
# TODO endpoint = "https://my-test-project.appspot.com/push"

subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
    project_id, subscription_name)

push_config = pubsub_v1.types.PushConfig(
    push_endpoint=endpoint)

subscription = pubsub_v1.types.Subscription(
    name=subscription_path,
    push_config=push_config)

update_mask = {
    'paths': {
        'push_config',
    }
}

subscriber.update_subscription(subscription, update_mask)
result = subscriber.get_subscription(subscription_path)

print('Subscription updated: {}'.format(subscription_path))
print('New endpoint for subscription is: {}'.format(
    result.push_config))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
# new_endpoint      = "Endpoint where your app receives messages""
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription          = pubsub.subscription subscription_name
subscription.endpoint = new_endpoint

puts "Push endpoint updated."

List subscriptions

You can list all subscriptions in a project, or only subscriptions to a particular topic. See Access Control for details on limiting access, if needed. Here are examples showing how to list all subscriptions in a project.

GCLOUD COMMAND

   gcloud pubsub subscriptions list

C#

Before trying this sample, follow the C# setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub C# API reference documentation .

SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
ProjectName projectName = new ProjectName(projectId);
IEnumerable<Subscription> subscriptions =
    subscriber.ListSubscriptions(projectName);
foreach (Subscription subscription in subscriptions)
{
    Console.WriteLine($"{subscription}");
}

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

var subs []*pubsub.Subscription
it := client.Subscriptions(ctx)
for {
	s, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	subs = append(subs, s)
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ListSubscriptionsRequest listSubscriptionsRequest =
      ListSubscriptionsRequest.newBuilder()
          .setProject(ProjectName.of(projectId).toString())
          .build();
  ListSubscriptionsPagedResponse response =
      subscriptionAdminClient.listSubscriptions(listSubscriptionsRequest);
  Iterable<Subscription> subscriptions = response.iterateAll();
  for (Subscription subscription : subscriptions) {
    // do something with the subscription
  }
  return response;
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

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

    console.log('Subscriptions:');
    subscriptions.forEach(subscription => console.log(subscription.name));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

use Google\Cloud\PubSub\PubSubClient;

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

Python

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"

subscriber = pubsub_v1.SubscriberClient()
project_path = subscriber.project_path(project_id)

for subscription in subscriber.list_subscriptions(project_path):
    print(subscription.name)

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id = Your Google Cloud Project ID
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscriptions = pubsub.list_subscriptions

puts "Subscriptions:"
subscriptions.each do |subscription|
  puts subscription.name
end

Here are examples showing how to access subscriptions for a specific topic.

GCLOUD COMMAND

   gcloud pubsub topics list-subscriptions myTopic

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

var subs []*pubsub.Subscription

it := client.Topic(topicID).Subscriptions(ctx)
for {
	sub, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	subs = append(subs, sub)
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
  ListTopicSubscriptionsRequest request =
      ListTopicSubscriptionsRequest.newBuilder()
          .setTopic(topicName.toString())
          .build();
  ListTopicSubscriptionsPagedResponse response =
      topicAdminClient.listTopicSubscriptions(request);
  Iterable<String> subscriptionNames = response.iterateAll();
  for (String subscriptionName : subscriptionNames) {
    // do something with the subscription name
  }
  return response;
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'my-topic';

// Lists all subscriptions for the topic
pubsub
  .topic(topicName)
  .getSubscriptions()
  .then(results => {
    const subscriptions = results[0];

    console.log(`Subscriptions for ${topicName}:`);
    subscriptions.forEach(subscription => console.log(subscription.name));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"

publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)

for subscription in publisher.list_topic_subscriptions(topic_path):
    print(subscription)

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic         = pubsub.topic topic_name
subscriptions = topic.subscriptions

puts "Subscriptions in topic #{topic.name}:"
subscriptions.each do |subscription|
  puts subscription.name
end

Delete a subscription

Here are examples showing how to delete subscriptions in a project once they are no longer required.

GCLOUD COMMAND

   gcloud pubsub subscriptions delete mySubscription

C#

Before trying this sample, follow the C# setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub C# API reference documentation .

SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId,
    subscriptionId);
subscriber.DeleteSubscription(subscriptionName);
Console.WriteLine("Subscription deleted.");

Go

Before trying this sample, follow the Go setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Go API reference documentation .

sub := client.Subscription(subName)
if err := sub.Delete(ctx); err != nil {
	return err
}
fmt.Println("Subscription deleted.")

Java

Before trying this sample, follow the Java setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Java API reference documentation .

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId);
  subscriptionAdminClient.deleteSubscription(subscriptionName);
  return subscriptionName;
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Node.js API reference documentation .

// Imports the Google Cloud client library
const PubSub = require(`@google-cloud/pubsub`);

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'my-sub';

// Deletes the subscription
pubsub
  .subscription(subscriptionName)
  .delete()
  .then(() => {
    console.log(`Subscription ${subscriptionName} deleted.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

Before trying this sample, follow the PHP setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub PHP API reference documentation .

use Google\Cloud\PubSub\PubSubClient;

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

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

Python

Before trying this sample, follow the Python setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Python API reference documentation .

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO subscription_name = "Your Pub/Sub subscription name"

subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(
    project_id, subscription_name)

subscriber.delete_subscription(subscription_path)

print('Subscription deleted: {}'.format(subscription_path))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Cloud Pub/Sub Quickstart Using Client Libraries . For more information, see the Cloud Pub/Sub Ruby API reference documentation .

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription = pubsub.subscription subscription_name
subscription.delete

puts "Subscription #{subscription_name} deleted."

Switching between push and pull subscriptions

You can use the Cloud Pub/Sub GCP Console to change the subscription type. In the console, edit the subscription and change the Delivery Type to Pull or Push.

Alternately, you can use the gcloud command line tool. Specifically, use modify-push-config to modify the push endpoint URL.

  • To convert a push subscription to pull, change the URL to an empty string.
  • To convert a pull subscription to push, set a valid URL.

Resource names

A Cloud Pub/Sub resource name uniquely identifies a Cloud Pub/Sub resource, such as a subscription or topic, and must fit the following format:

projects/project-identifier/collection/relative-name

The project-identifier must be the project ID, available from the Google Cloud Platform Console. For example, projects/myproject/topics/mytopic.

The collection must be one of subscriptions or topics.

The relative-name must:

  • Start with a letter
  • Contain between 3 and 255 characters
  • Contain only the following characters:

    • Letters: [A-Za-z]
    • Numbers: [0-9]
    • Dashes: -
    • Underscores: _
    • Periods: .
    • Tildes: ~
    • Plus signs: +
    • Percent signs: %

      While the above-mentioned special characters can be used in resource names, you must ensure that the characters are properly encoded/decoded when used in URLs. This is particularly important for REST calls.

The relative-name must not begin with the string goog.

You can include special characters in the resource name. For example, mi-tópico is an invalid relative-name. However, mi-t%C3%B3pico is valid.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Pub/Sub Documentation