Managing topics and subscriptions

This document provides information about how to create, delete, and administer Pub/Sub topics and subscriptions. For more information about publishing and accessing message data, see the Publisher Guide and Subscriber Overview.

Managing Topics

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

Creating 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:

gcloud

gcloud pubsub topics create TOPIC_ID

REST

Request:

The request must be authenticated with an access token in the Authorization header. To obtain an access token for the current Application Default Credentials: gcloud auth application-default print-access-token.

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

Response:

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

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string topic_id) {
  auto topic = client.CreateTopic(pubsub::TopicBuilder(
      pubsub::Topic(std::move(project_id), std::move(topic_id))));
  // Note that kAlreadyExists is a possible error when the library retries.
  if (topic.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The topic already exists\n";
    return;
  }
  if (!topic) throw std::runtime_error(topic.status().message());

  std::cout << "The topic was successfully created: " << topic->DebugString()
            << "\n";
}

C#

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


using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;

public class CreateTopicSample
{
    public Topic CreateTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        var topicName = TopicName.FromProjectTopic(projectId, topicId);
        Topic topic = null;

        try
        {
            topic = publisher.CreateTopic(topicName);
            Console.WriteLine($"Topic {topic.Name} created.");
        }
        catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            Console.WriteLine($"Topic {topicName} already exists.");
        }
        return topic;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func create(w io.Writer, projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

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

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreateTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    createTopicExample(projectId, topicId);
  }

  public static void createTopicExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      Topic topic = topicAdminClient.createTopic(topicName);
      System.out.println("Created topic: " + topic.getName());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createTopic() {
  // Creates a new topic
  await pubSubClient.createTopic(topicName);
  console.log(`Topic ${topicName} created.`);
}

createTopic();

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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 Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

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

topic = publisher.create_topic(request={"name": topic_path})

print("Created topic: {}".format(topic.name))

Ruby

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

# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic = pubsub.create_topic topic_name

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

Deleting a topic

Here is an example showing how to delete a topic:

gcloud

gcloud pubsub topics delete TOPIC_ID

REST

Request:

The request must be authenticated with an access token in the Authorization header. To obtain an access token for the current Application Default Credentials: gcloud auth application-default print-access-token.

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

Response:

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

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string const& project_id,
   std::string const& topic_id) {
  auto status = client.DeleteTopic(
      pubsub::Topic(std::move(project_id), std::move(topic_id)));
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The topic was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The topic was successfully deleted\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class DeleteTopicSample
{
    public void DeleteTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        publisher.DeleteTopic(topicName);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func delete(w io.Writer, projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

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

Java

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


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class DeleteTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    deleteTopicExample(projectId, topicId);
  }

  public static void deleteTopicExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      try {
        topicAdminClient.deleteTopic(topicName);
        System.out.println("Deleted topic.");
      } catch (NotFoundException e) {
        System.out.println(e.getMessage());
      }
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

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

  // Deletes the topic
  await pubSubClient.topic(topicName).delete();
  console.log(`Topic ${topicName} deleted.`);
}

deleteTopic().catch(console.error);

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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 Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

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

publisher.delete_topic(request={"topic": topic_path})

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

Ruby

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

# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

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.

Listing topics

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

gcloud

gcloud pubsub topics list

REST

Request:

The request must be authenticated with an access token in the Authorization header. To obtain an access token for the current Application Default Credentials: gcloud auth application-default print-access-token.

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

Response:

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

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string const& project_id) {
  int count = 0;
  for (auto const& topic : client.ListTopics(project_id)) {
    if (!topic) throw std::runtime_error(topic.status().message());
    std::cout << "Topic Name: " << topic->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No topics found in project " << project_id << "\n";
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListProjectTopicsSample
{
    public IEnumerable<Topic> ListProjectTopics(string projectId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        ProjectName projectName = ProjectName.FromProject(projectId);
        IEnumerable<Topic> topics = publisher.ListTopics(projectName);
        return topics;
    }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func list(projectID string) ([]*pubsub.Topic, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	var topics []*pubsub.Topic

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

	return topics, nil
}

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Topic;
import java.io.IOException;

public class ListTopicsExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";

    listTopicsExample(projectId);
  }

  public static void listTopicsExample(String projectId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      ProjectName projectName = ProjectName.of(projectId);
      for (Topic topic : topicAdminClient.listTopics(projectName).iterateAll()) {
        System.out.println(topic.getName());
      }
      System.out.println("Listed all topics.");
    }
  }
}

Node.js

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

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function listAllTopics() {
  // Lists all topics in the current project
  const [topics] = await pubSubClient.getTopics();
  console.log('Topics:');
  topics.forEach(topic => console.log(topic.name));
}

listAllTopics().catch(console.error);

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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 Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"

publisher = pubsub_v1.PublisherClient()
project_path = f"projects/{project_id}"

for topic in publisher.list_topics(request={"project": project_path}):
    print(topic)

Ruby

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

require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

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.

Detaching subscriptions

When you create a subscription, you attach the subscription to a topic, and subscribers can receive messages from the subscription. To stop subscribers from receiving messages, you can detach subscriptions from the topic.

Before you detach a subscription, you need the pubsub.topics.detachSubscription permission on the topic. You can detach a subscription without permissions on the subscription, which is useful for managing a topic that is in a different project than the subscription. For more information, see Pub/Sub access control.

You can detach a subscription from a topic using the Cloud Console, the gcloud command-line tool, or the Pub/Sub API.

Console

To detach a subscription, follow these steps:

  1. In the Cloud Console, go to the Topics page.

    Go to the Topics page

  2. Click the topic ID.
  3. In the Subscriptions tab, click the subscription ID of the subscription to detach.
  4. In the Subscription details page, click Detach.
  5. In the dialog that appears, click Detach again.

gcloud

To detach a subscription, use the gcloud pubsub topics detach-subscription command:

gcloud pubsub topics detach-subscription SUBSCRIPTION_ID

If the request is successful, the command line displays a confirmation:

Detached subscription [SUBSCRIPTION_ID].

REST

To detach a subscription, send a request like the following:

POST https://pubsub.googleapis.com/v1/subscriptions/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:detach
Authorization: Bearer $(gcloud auth application-default print-access-token)

If the request is successful, the response is an empty JSON object.

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string subscription_id) {
  auto response = client.DetachSubscription(pubsub::Subscription(
      std::move(project_id), std::move(subscription_id)));
  if (!response.ok()) return;  // TODO(#4792) - not implemented in emulator

  std::cout << "The subscription was successfully detached: "
            << response->DebugString() << "\n";
}

C#

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


using Google.Cloud.PubSub.V1;
using System;

public class DetachSubscriptionSample
{
    public void DetachSubscription(string projectId, string subscriptionId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();

        DetachSubscriptionRequest detachSubscriptionRequest = new DetachSubscriptionRequest
        {
            SubscriptionAsSubscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
        };

        publisher.DetachSubscription(detachSubscriptionRequest);

        Console.WriteLine($"Subscription {subscriptionId} is detached.");
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func detachSubscription(w io.Writer, projectID, subName string) error {
	// projectID is the project which contains the topic you manage.
	// This might differ from the project which contains the subscription
	// you wish to detach, which can exist in any GCP project.
	// projectID := "my-project-id"
	// subName := "projects/some-project/subscriptions/my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}
	defer client.Close()

	// Call DetachSubscription, which detaches a subscription from
	// a topic. This can only be done if you have the
	// `pubsub.topics.detachSubscription` role on the topic.
	_, err = client.DetachSubscription(ctx, subName)
	if err != nil {
		return fmt.Errorf("detach subscription failed: %v", err)
	}

	fmt.Fprintf(w, "Detached subscription %s", subName)
	return nil
}

Java

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

import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.DetachSubscriptionRequest;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class DetachSubscriptionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    // Choose an existing subscription.
    String subscriptionId = "your-subscription-id";

    detachSubscriptionExample(projectId, subscriptionId);
  }

  public static void detachSubscriptionExample(String projectId, String subscriptionId)
      throws IOException {
    ProjectSubscriptionName subscriptionName =
        ProjectSubscriptionName.of(projectId, subscriptionId);

    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      topicAdminClient.detachSubscription(
          DetachSubscriptionRequest.newBuilder()
              .setSubscription(subscriptionName.toString())
              .build());
    }

    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
      if (subscription.getDetached()) {
        System.out.println("Subscription is detached.");
      } else {
        System.out.println("Subscription is NOT detached.");
      }
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const subscriptionName = 'YOUR_EXISTING_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function detachSubscription() {
  // Gets the status of the existing subscription
  const sub = pubSubClient.subscription(subscriptionName);
  const [detached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionName} 'before' detached status: ${detached}`
  );

  await pubSubClient.detachSubscription(subscriptionName);
  console.log(`Subscription ${subscriptionName} detach request was sent.`);

  const [updatedDetached] = await sub.detached();
  console.log(
    `Subscription ${subscriptionName} 'after' detached status: ${updatedDetached}`
  );
}

detachSubscription();

PHP

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

use Google\Cloud\PubSub\PubSubClient;

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

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

Python

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

from google.api_core.exceptions import GoogleAPICallError, RetryError
from google.cloud import pubsub_v1

# TODO(developer): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

publisher_client = pubsub_v1.PublisherClient()
subscriber_client = pubsub_v1.SubscriberClient()
subscription_path = subscriber_client.subscription_path(project_id, subscription_id)

try:
    publisher_client.detach_subscription(
        request={"subscription": subscription_path}
    )
except (GoogleAPICallError, RetryError, ValueError, Exception) as err:
    print(err)

subscription = subscriber_client.get_subscription(
    request={"subscription": subscription_path}
)
if subscription.detached:
    print(f"{subscription_path} is detached.")
else:
    print(f"{subscription_path} is NOT detached.")

Ruby

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

# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_name
subscription.detach

sleep 120
subscription.reload!
if subscription.detached?
  puts "Subscription is detached."
else
  puts "Subscription is NOT detached."
end

The Pub/Sub service might take several minutes to finish detaching the subscription from the topic.

After the Pub/Sub service detaches the subscription from the topic, the Pub/Sub service deletes any messages that it retains for the subscription. You can't retrieve these messages from the subscription or reattach the subscription to a topic. To free up your Cloud project quota, delete the subscription.

If the subscription and the topic are in different Cloud projects, the Pub/Sub service adds an entry to the audit logs of both projects.

Managing Subscriptions

This section covers how to manage push and pull subscriptions. See the Subscriber Overview for an overview and comparison of pull and push subscriptions.

You must create a subscription to a topic before subscribers can receive messages published to the topic.

Creating subscriptions

You can create subscriptions with the Cloud Console, gcloud command-line tool, or the Pub/Sub API.

Console

To create a subscription, complete the following steps.

  1. In the Cloud Console, go to the Subscriptions page.

    Go to the Subscriptions page

  2. Click Create subscription.
  3. Enter the Subscription ID.
  4. Choose or create a topic from the drop-down menu. The subscription receives messages from the topic.
  5. Click Create.

You can also create a subscription from the Topics section. This shortcut is useful for associating topics with subscriptions.

  1. In the Cloud Console, go to the Topics page.

    Go to the Topics page

  2. Clicknext to the topic on which to create a subscription.
  3. From the context menu, select Create subscription.

    The context menu with the Create subscription option highlighted.

  4. Choose or create a topic from the drop-down menu. The subscription receives messages from the topic.
  5. Enter the Subscription ID.
  6. Click Create.

gcloud

To create a subscription, run the gcloud pubsub subscriptions create command.

gcloud pubsub subscriptions create SUBSCRIPTION_ID \
    --topic=TOPIC_ID \
    [--ack-deadline=ACK_DEADLINE] \
    [--message-retention-duration=MESSAGE_RETENTION_DURATION] \
    [--expiration-period=EXPIRATION_PERIOD] \
    [--push-endpoint=PUSH_ENDPOINT] \
    [--dead-letter-topic=DEAD_LETTER_TOPIC_ID \
    --max-delivery-attempts=MAX_DELIVERY_ATTEMPTS] \
    [--min-retry-delay=MIN_RETRY_DELAY] \
    [--max-retry-delay=MAX_RETRY_DELAY]

REST

Request:

The request must be authenticated with an access token in the Authorization header. To obtain an access token for the current Application Default Credentials: gcloud auth application-default print-access-token.

PUT https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription
Authorization: Bearer ACCESS_TOKEN

Specify the following fields in the request body:

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

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& topic_id, std::string const& subscription_id) {
  auto sub = client.CreateSubscription(
      pubsub::Topic(project_id, std::move(topic_id)),
      pubsub::Subscription(project_id, std::move(subscription_id)));
  if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The subscription already exists\n";
    return;
  }
  if (!sub) throw std::runtime_error(sub.status().message());

  std::cout << "The subscription was successfully created: "
            << sub->DebugString() << "\n";
}

C#

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


using Google.Cloud.PubSub.V1;
using Grpc.Core;

public class CreateSubscriptionSample
{
    public Subscription CreateSubscription(string projectId, string topicId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);

        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        Subscription subscription = null;

        try
        {
            subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
        }
        catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            // Already exists.  That's fine.
        }
        return subscription;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/pubsub"
)

func create(w io.Writer, projectID, subID string, topic *pubsub.Topic) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	// topic of type https://godoc.org/cloud.google.com/go/pubsub#Topic
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

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

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreatePullSubscriptionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";
    String topicId = "your-topic-id";

    createPullSubscriptionExample(projectId, subscriptionId, topicId);
  }

  public static void createPullSubscriptionExample(
      String projectId, String subscriptionId, String topicId) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      // Create a pull subscription with default acknowledgement deadline of 10 seconds.
      // Messages not successfully acknowledged within 10 seconds will get resent by the server.
      Subscription subscription =
          subscriptionAdminClient.createSubscription(
              subscriptionName, topicName, PushConfig.getDefaultInstance(), 10);
      System.out.println("Created pull subscription: " + subscription.getName());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createSubscription() {
  // Creates a new subscription
  await pubSubClient.topic(topicName).createSubscription(subscriptionName);
  console.log(`Subscription ${subscriptionName} created.`);
}

createSubscription().catch(console.error);

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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 Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"

publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic_path = publisher.topic_path(project_id, topic_id)
subscription_path = subscriber.subscription_path(project_id, subscription_id)

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    subscription = subscriber.create_subscription(
        request={"name": subscription_path, "topic": topic_path}
    )

print(f"Subscription created: {subscription}")

Ruby

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

# topic_name        = "Your Pubsub topic name"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

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

puts "Pull subscription #{subscription_name} created."

The following samples demonstrate how to create a subscription with push delivery. By default, subscriptions use pull delivery.

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& topic_id, std::string const& subscription_id,
   std::string const& endpoint) {
  auto sub = client.CreateSubscription(
      pubsub::Topic(project_id, std::move(topic_id)),
      pubsub::Subscription(project_id, std::move(subscription_id)),
      pubsub::SubscriptionBuilder{}.set_push_config(
          pubsub::PushConfigBuilder{}.set_push_endpoint(endpoint)));
  if (sub.status().code() == google::cloud::StatusCode::kAlreadyExists) {
    std::cout << "The subscription already exists\n";
    return;
  }
  if (!sub) throw std::runtime_error(sub.status().message());

  std::cout << "The subscription was successfully created: "
            << sub->DebugString() << "\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class CreatePushSubscriptionSample
{
    public Subscription CreatePushSubscription(string projectId, string topicId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint };

        // The approximate amount of time in seconds (on a best-effort basis) Pub/Sub waits for the
        // subscriber to acknowledge receipt before resending the message.
        var ackDeadlineSeconds = 60;
        var subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig, ackDeadlineSeconds);
        return subscription;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/pubsub"
)

func createWithEndpoint(w io.Writer, projectID, subID string, topic *pubsub.Topic, endpoint string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	// topic of type https://godoc.org/cloud.google.com/go/pubsub#Topic
	// endpoint := "https://my-test-project.appspot.com/push"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	sub, err := client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{
		Topic:       topic,
		AckDeadline: 10 * time.Second,
		PushConfig:  pubsub.PushConfig{Endpoint: endpoint},
	})
	if err != nil {
		return fmt.Errorf("CreateSubscription: %v", err)
	}
	fmt.Fprintf(w, "Created subscription: %v\n", sub)
	return nil
}

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class CreatePushSubscriptionExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";
    String topicId = "your-topic-id";
    String pushEndpoint = "https://my-test-project.appspot.com/push";

    createPushSubscriptionExample(projectId, subscriptionId, topicId, pushEndpoint);
  }

  public static void createPushSubscriptionExample(
      String projectId, String subscriptionId, String topicId, String pushEndpoint)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build();

      // Create a push subscription with default acknowledgement deadline of 10 seconds.
      // Messages not successfully acknowledged within 10 seconds will get resent by the server.
      Subscription subscription =
          subscriptionAdminClient.createSubscription(subscriptionName, topicName, pushConfig, 10);
      System.out.println("Created push subscription: " + subscription.getName());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function createPushSubscription() {
  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://${pubSubClient.projectId}.appspot.com/push`,
    },
  };

  await pubSubClient
    .topic(topicName)
    .createSubscription(subscriptionName, options);
  console.log(`Subscription ${subscriptionName} created.`);
}

createPushSubscription().catch(console.error);

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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([
        'pushConfig' => ['pushEndpoint' => $endpoint]
    ]);

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

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# endpoint = "https://my-test-project.appspot.com/push"

publisher = pubsub_v1.PublisherClient()
subscriber = pubsub_v1.SubscriberClient()
topic_path = publisher.topic_path(project_id, topic_id)
subscription_path = subscriber.subscription_path(project_id, subscription_id)

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

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    subscription = subscriber.create_subscription(
        request={
            "name": subscription_path,
            "topic": topic_path,
            "push_config": push_config,
        }
    )

print(f"Push subscription created: {subscription}.")
print(f"Endpoint for subscription is: {endpoint}")

Ruby

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

# 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

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

puts "Push subscription #{subscription_name} created."

Using subscription properties

You can set subscription properties when you create or update a subscription. For more information about setting subscription properties with gcloud command-line tool, see the gcloud pubsub subscriptions create or gcloud pubsub subscriptions update optional flags.

Subscriptions have the following properties:

Property Description Default
Delivery method

You can receive messages with pull or push delivery. In pull delivery, your subscriber application initiates requests to the Pub/Sub server to retrieve messages. In push delivery, Pub/Sub initiates requests to your subscriber application to deliver messages.

If unspecified, Pub/Sub subscriptions use pull delivery.

Acknowledgement deadline

If your code doesn't acknowledge the message before the deadline, the message is sent again.

10 seconds is the default acknowledgement deadline. The maximum is 10 minutes.

Message retention duration

The message retention duration specifies how long Pub/Sub retains messages after publication. After the message retention duration Pub/Sub might discard the message, regardless of its acknowledgement state.

To retain acknowledged messages for the message retention duration, see Replaying and discarding messages.

7 days is the default message retention duration. The minimum is 10 minutes and the maximum is 7 days.
Dead-letter topics

When a subscriber can't acknowledge a message, Pub/Sub can forward the message to a dead-letter topic. For details, see Forwarding to dead-letter topics.

If you use a dead-letter topic, you can't enable message ordering.

If you set a dead-letter topic, you can also specify the maximum number of delivery attempts. The default is 5 delivery attempts and you can specify 5-100 delivery attempts.

If you set a dead-letter topic and the topic is in a different project than the subscription, you must also specify the project ID with the dead-letter topic.

Expiration period

Subscriptions without subscriber activity (such as open connections, active pulls, or successful pushes) expire. If Pub/Sub detects subscriber activity, the subscription deletion clock restarts.

31 days is the default expiration period. The minimum is 1 day.

To prevent a subscription from expiring, set the expiration period to never.

Retry policy

If the acknowledgement deadline expires or a subscriber responds with a negative acknowledgement, Pub/Sub can send the message again using exponential backoff.

If the retry policy isn't set, Pub/Sub resends the message as soon as the acknowledgement deadline expires or a subscriber responds with a negative acknowledgement.

If the maximum backoff duration is set, the default minimum backoff duration is 10 seconds. If the minimum backoff duration is set, the default maximum backoff duration is 600 seconds.

The longest backoff duration that you can specify is 600 seconds.

Message ordering

If publishers send messages with an ordering key and message ordering is set, Pub/Sub delivers the messages in order.

If not set, Pub/Sub doesn't deliver messages in order, including messages with ordering keys.

Filter

The filter is a string with a filtering expression. If a subscription has a filter, the subscription only delivers the messages that match the filter. You can filter messages by their attributes.

If unspecified, the subscription doesn't filter messages and subscribers receive all of the messages.

Using retry policies

When a subscription has a retry policy, Pub/Sub resends messages on a best-effort basis. You might receive messages before the minimum backoff duration.

If messages are in a batch and the subscription has a retry policy, Pub/Sub resends the batch when one of the following occurs:

  • The subscriber sends a negative acknowledgement for every message in the batch.
  • The acknowledgement deadline expires.

Modifying delivery methods

You can switch between push and pull subscriptions with the Cloud Console, gcloud command-line tool, or the Pub/Sub API.

Console

To modify a push subscription, complete the following steps.

  1. In the Cloud Console, go to the Subscriptions page.

    Go to the Subscriptions page

  2. Clicknext to the subscription to update.

    The context menu with the Edit option highlighted.

  3. In the Delivery Type, choose Pull or Push.
  4. Click Update.

gcloud

To modify the push endpoint URL, run the modify-push-config command:

gcloud pubsub subscriptions modify-push-config SUBSCRIPTION_ID \
    --push-endpoint=PUSH_ENDPOINT

If the subscription is already using pull delivery, setting the push endpoint switches the delivery method to push delivery.

You can switch from push to pull delivery by changing the push endpoint to an empty string.

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& subscription_id, std::string const& endpoint) {
  auto status = client.ModifyPushSubscription(
      pubsub::Subscription(project_id, std::move(subscription_id)),
      pubsub::PushConfigBuilder{}.set_push_endpoint(endpoint));
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription push configuration was successfully"
            << " modified\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class UpdatePushConfigurationSample
{
    public void UpdatePushConfiguration(string projectId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint };

        subscriber.ModifyPushConfig(subscriptionName, pushConfig);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func updateEndpoint(w io.Writer, projectID, subID string, endpoint string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	// endpoint := "https://my-test-project.appspot.com/push"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	subConfig, err := client.Subscription(subID).Update(ctx, pubsub.SubscriptionConfigToUpdate{
		PushConfig: &pubsub.PushConfig{Endpoint: endpoint},
	})
	if err != nil {
		return fmt.Errorf("Update: %v", err)
	}
	fmt.Fprintf(w, "Updated subscription config: %v\n", subConfig)
	return nil
}

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PushConfig;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class UpdatePushConfigurationExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";
    String pushEndpoint = "https://my-test-project.appspot.com/push";

    updatePushConfigurationExample(projectId, subscriptionId, pushEndpoint);
  }

  public static void updatePushConfigurationExample(
      String projectId, String subscriptionId, String pushEndpoint) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(pushEndpoint).build();
      subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
      Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
      System.out.println(
          "Updated push endpoint to: " + subscription.getPushConfig().getPushEndpoint());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

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

  await pubSubClient
    .topic(topicName)
    .subscription(subscriptionName)
    .modifyPushConfig(options);
  console.log(`Modified push config for subscription ${subscriptionName}.`);
}

modifyPushConfig().catch(console.error);

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# endpoint = "https://my-test-project.appspot.com/push"

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

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

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

update_mask = {"paths": {"push_config"}}

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    result = subscriber.update_subscription(
        request={"subscription": subscription, "update_mask": update_mask}
    )

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

Ruby

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

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

pubsub = Google::Cloud::Pubsub.new

subscription          = pubsub.subscription subscription_name
subscription.endpoint = new_endpoint

puts "Push endpoint updated."

Listing subscriptions

You can list the subscriptions in a Google Cloud project with the Cloud Console, gcloud command-line tool, or Pub/Sub API.

Console

To list the subscriptions in a project, go to the Subscriptions page.

Go to the Subscriptions page

gcloud

To list the subscriptions in a Google Cloud project, run the gcloud pubsub subscriptions list command:

gcloud pubsub subscriptions list [--project=PROJECT_ID]

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id) {
  int count = 0;
  for (auto const& subscription : client.ListSubscriptions(project_id)) {
    if (!subscription)
      throw std::runtime_error(subscription.status().message());
    std::cout << "Subscription Name: " << subscription->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No subscriptions found in project " << project_id << "\n";
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListSubscriptionsSample
{
    public IEnumerable<Subscription> ListSubscriptions(string projectId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        ProjectName projectName = ProjectName.FromProject(projectId);
        var subscriptions = subscriber.ListSubscriptions(projectName);
        return subscriptions;
    }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func list(projectID string) ([]*pubsub.Subscription, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

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

Java

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


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Subscription;
import java.io.IOException;

public class ListSubscriptionsInProjectExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";

    listSubscriptionInProjectExample(projectId);
  }

  public static void listSubscriptionInProjectExample(String projectId) throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectName projectName = ProjectName.of(projectId);
      for (Subscription subscription :
          subscriptionAdminClient.listSubscriptions(projectName).iterateAll()) {
        System.out.println(subscription.getName());
      }
      System.out.println("Listed all the subscriptions in the project.");
    }
  }
}

Node.js

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

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function listSubscriptions() {
  // Lists all subscriptions in the current project
  const [subscriptions] = await pubSubClient.getSubscriptions();
  console.log('Subscriptions:');
  subscriptions.forEach(subscription => console.log(subscription.name));
}

listSubscriptions().catch(console.error);

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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 Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"

subscriber = pubsub_v1.SubscriberClient()
project_path = f"projects/{project_id}"

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    for subscription in subscriber.list_subscriptions(
        request={"project": project_path}
    ):
        print(subscription.name)

Ruby

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

require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

subscriptions = pubsub.list_subscriptions

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

You can list the subscriptions to a topic with the Cloud Console, gcloud command-line tool, or Pub/Sub API.

Console

  1. In the Cloud Console, go to the Topics page.

    Go to the Topics page

  2. Select a topic ID to open the Topic details page. The Subscriptions section of the page includes of list of subscriptions to the topic.

gcloud

To list the subscriptions in a Google Cloud project, run the gcloud pubsub topics list-subscriptions command:

gcloud pubsub topics list-subscriptions TOPIC_ID

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::TopicAdminClient client, std::string project_id,
   std::string topic_id) {
  auto const topic =
      pubsub::Topic(std::move(project_id), std::move(topic_id));
  std::cout << "Subscription list for topic " << topic << ":\n";
  for (auto const& name : client.ListTopicSubscriptions(topic)) {
    if (!name) throw std::runtime_error(name.status().message());
    std::cout << "  " << *name << "\n";
  }
}

C#

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


using Google.Cloud.PubSub.V1;
using System.Collections.Generic;

public class ListSubscriptionsInTopicSample
{
    public IEnumerable<string> ListSubscriptionsInTopic(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        IEnumerable<string> subscriptions = publisher.ListTopicSubscriptions(topicName);
        return subscriptions;
    }
}

Go

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

import (
	"context"
	"fmt"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func listSubscriptions(projectID, topicID string) ([]*pubsub.Subscription, error) {
	// projectID := "my-project-id"
	// topicName := "projects/sample-248520/topics/ocr-go-test-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %v", err)
	}

	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, fmt.Errorf("Next: %v", err)
		}
		subs = append(subs, sub)
	}
	return subs, nil
}

Java

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


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class ListSubscriptionsInTopicExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    listSubscriptionInTopicExample(projectId, topicId);
  }

  public static void listSubscriptionInTopicExample(String projectId, String topicId)
      throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      for (String subscription : topicAdminClient.listTopicSubscriptions(topicName).iterateAll()) {
        System.out.println(subscription);
      }
      System.out.println("Listed all the subscriptions in the topic.");
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicName = 'YOUR_TOPIC_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function listTopicSubscriptions() {
  // Lists all subscriptions for the topic
  const [subscriptions] = await pubSubClient
    .topic(topicName)
    .getSubscriptions();

  console.log(`Subscriptions for ${topicName}:`);
  subscriptions.forEach(subscription => console.log(subscription.name));
}

listTopicSubscriptions().catch(console.error);

Python

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

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# topic_id = "your-topic-id"

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

response = publisher.list_topic_subscriptions(request={"topic": topic_path})
for subscription in response:
    print(subscription)

Ruby

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

# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

topic         = pubsub.topic topic_name
subscriptions = topic.subscriptions

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

Deleting subscriptions

You can delete subscriptions with the Cloud Console, gcloud command-line tool, or Pub/Sub API.

Console

  1. In the Cloud Console, go to the Subscriptions page.

    Go to the Subscriptions page

  2. Select the subscription to delete.
  3. Click Delete.

gcloud

To delete a subscription, run the gcloud pubsub subscriptions delete command:

gcloud pubsub subscriptions delete SUBSCRIPTION_ID

C++

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

namespace pubsub = google::cloud::pubsub;
[](pubsub::SubscriptionAdminClient client, std::string const& project_id,
   std::string const& subscription_id) {
  auto status = client.DeleteSubscription(pubsub::Subscription(
      std::move(project_id), std::move(subscription_id)));
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The subscription was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "The subscription was successfully deleted\n";
}

C#

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


using Google.Cloud.PubSub.V1;

public class DeleteSubscriptionSample
{
    public void DeleteSubscription(string projectId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        subscriber.DeleteSubscription(subscriptionName);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

func delete(w io.Writer, projectID, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %v", err)
	}

	sub := client.Subscription(subID)
	if err := sub.Delete(ctx); err != nil {
		return fmt.Errorf("Delete: %v", err)
	}
	fmt.Fprintf(w, "Subscription %q deleted.", subID)
	return nil
}

Java

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


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;

public class DeleteSubscriptionExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    deleteSubscriptionExample(projectId, subscriptionId);
  }

  public static void deleteSubscriptionExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      try {
        subscriptionAdminClient.deleteSubscription(subscriptionName);
        System.out.println("Deleted subscription.");
      } catch (NotFoundException e) {
        System.out.println(e.getMessage());
      }
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionName = 'YOUR_SUBSCRIPTION_NAME';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function deleteSubscription() {
  // Deletes the subscription
  await pubSubClient.subscription(subscriptionName).delete();
  console.log(`Subscription ${subscriptionName} deleted.`);
}

deleteSubscription().catch(console.error);

PHP

Before trying this sample, follow the PHP setup instructions in the Pub/Sub Quickstart Using Client Libraries. For more information, see the 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 Pub/Sub Quickstart Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

from google.cloud import pubsub_v1

# TODO(developer)
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

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

# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
    subscriber.delete_subscription(request={"subscription": subscription_path})

print(f"Subscription deleted: {subscription_path}.")

Ruby

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

# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_name
subscription.delete

puts "Subscription #{subscription_name} deleted."

Resource names

A Pub/Sub resource name uniquely identifies a 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 Console. For example, projects/myproject/topics/mytopic.

The collection must be one of subscriptions or topics.

The relative-name must:

  • Not begin with the string goog.
  • 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: %

      The special characters in the above list can be used in resource names without URL-encoding. However, you must ensure that any other special characters are properly encoded/decoded when used in URLs. For example, mi-tópico is an invalid relative-name. However, mi-t%C3%B3pico is valid.

      This is particularly important for REST calls.