List subscriptions

You can list the subscriptions in a Google Cloud project with the Google Cloud console, Google Cloud CLI, client library, or Pub/Sub API.

Before you begin

Required roles and permissions

To get the permissions that you need to list subscriptions and manage them, ask your administrator to grant you the Pub/Sub Editor (roles/pubsub.editor) IAM role on your topic or project. For more information about granting roles, see Manage access to projects, folders, and organizations.

This predefined role contains the permissions required to list subscriptions and manage them. To see the exact permissions that are required, expand the Required permissions section:

Required permissions

The following permissions are required to list subscriptions and manage them:

  • Pull from a subscription: pubsub.subscriptions.consume
  • Create a subscription: pubsub.subscriptions.create
  • Delete a subscription: pubsub.subscriptions.delete
  • Get a subscription: pubsub.subscriptions.get
  • List a subscription: pubsub.subscriptions.list
  • Update a subscription: pubsub.subscriptions.update
  • Attach a subscription to a topic: pubsub.topics.attachSubscription
  • Get the IAM policy for a subscription: pubsub.subscriptions.getIamPolicy
  • Configure the IAM policy for a subscription: pubsub.subscriptions.setIamPolicy

You might also be able to get these permissions with custom roles or other predefined roles.

List a subscription

You can list the subscriptions in a Google Cloud project with the Google Cloud console, Google Cloud CLI, client library, or Pub/Sub API.

Console

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

Go to Subscriptions

Your subscriptions are listed in the table on the page.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

    gcloud pubsub subscriptions list [--project=PROJECT_ID]

REST

To list subscriptions in a project, use the projects.subscriptions.list method:

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/PROJECT_ID/subscriptions
Authorization: Bearer ACCESS_TOKEN
    

Where:

  • PROJECT_ID is your project ID.
  • Response:

    {
      "subscriptions": [
        {
          "name": "projects/PROJECT_ID/topics/mysubscription1",
          "topic": "projects/PROJECT_ID/topics/TOPIC_ID",
          "pushConfig": {},
          "ackDeadlineSeconds": 10,
          "retainAckedMessages": true,
          "messageRetentionDuration": "604800s",
          "expirationPolicy": {}
        },
        {
          "name": "projects/PROJECT_ID/topics/mysubscription2",
          "topic": "projects/PROJECT_ID/topics/TOPIC_ID",
          "pushConfig": {
            "pushEndpoint": "https://PROJECT_ID.appspot.com/myhandler",
            "attributes": {
              "x-goog-version": "v1"
            }
          },
          "ackDeadlineSeconds": 10,
          "retainAckedMessages": true,
          "messageRetentionDuration": "604800s",
          "expirationPolicy": {}
        }
      ]
    }

    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    [](pubsub_admin::SubscriptionAdminClient client,
       std::string const& project_id) {
      int count = 0;
      google::pubsub::v1::ListSubscriptionsRequest request;
      request.set_project(google::cloud::Project(project_id).FullName());
      for (auto& subscription : client.ListSubscriptions(request)) {
        if (!subscription) throw std::move(subscription).status();
        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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    
    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    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: %w", err)
    	}
    	defer client.Close()
    
    	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: %w", 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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    
    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

    // 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));
    }

    Node.js

    // Imports the Google Cloud client library
    import {PubSub, Subscription} from '@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: Subscription) =>
        console.log(subscription.name)
      );
    }

    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    
    pubsub = Google::Cloud::Pubsub.new
    
    subscriptions = pubsub.list_subscriptions
    
    puts "Subscriptions:"
    subscriptions.each do |subscription|
      puts subscription.name
    end

    List subscriptions to a topic

    You can list the subscriptions to a topic with the Google Cloud console, Google Cloud CLI, or Pub/Sub API.

    Console

    1. In the Google Cloud console, go to the Topics page.

      Go to Topics

    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

    1. In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

      gcloud pubsub topics list-subscriptions TOPIC_ID

    REST

    To list subscriptions in a topic, use the projects.subscriptions.list method:

    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/PROJECT_ID/topics/TOPIC_ID/subscriptions
    Authorization: Bearer ACCESS_TOKEN
        

    Where:

  • PROJECT_ID is your project ID.
  • TOPIC_ID is your topic ID.
  • Response:

    {
      "subscriptions": [
        "projects/PROJECT_ID/subscriptions/mysubscription1",
        "projects/PROJECT_ID/subscriptions/mysubscription2"
      ]
    }

    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    namespace pubsub_admin = ::google::cloud::pubsub_admin;
    namespace pubsub = ::google::cloud::pubsub;
    [](pubsub_admin::TopicAdminClient client, std::string const& project_id,
       std::string const& topic_id) {
      auto const topic = pubsub::Topic(project_id, topic_id);
      std::cout << "Subscription list for topic " << topic << ":\n";
      for (auto& name : client.ListTopicSubscriptions(topic.FullName())) {
        if (!name) throw std::move(name).status();
        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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    
    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    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: %w", err)
    	}
    	defer client.Close()
    
    	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: %w", 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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    
    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

    /**
     * TODO(developer): Uncomment this variable before running the sample.
     */
    // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
    
    // 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(topicNameOrId) {
      // Lists all subscriptions for the topic
      const [subscriptions] = await pubSubClient
        .topic(topicNameOrId)
        .getSubscriptions();
    
      console.log(`Subscriptions for ${topicNameOrId}:`);
      subscriptions.forEach(subscription => console.log(subscription.name));
    }

    Node.js

    /**
     * TODO(developer): Uncomment this variable before running the sample.
     */
    // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
    
    // Imports the Google Cloud client library
    import {PubSub, Subscription} from '@google-cloud/pubsub';
    
    // Creates a client; cache this for further use
    const pubSubClient = new PubSub();
    
    async function listTopicSubscriptions(topicNameOrId: string) {
      // Lists all subscriptions for the topic
      const [subscriptions] = await pubSubClient
        .topic(topicNameOrId)
        .getSubscriptions();
    
      console.log(`Subscriptions for ${topicNameOrId}:`);
      subscriptions.forEach((subscription: Subscription) =>
        console.log(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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    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.

    To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

    # topic_id = "your-topic-id"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic         = pubsub.topic topic_id
    subscriptions = topic.subscriptions
    
    puts "Subscriptions in topic #{topic.name}:"
    subscriptions.each do |subscription|
      puts subscription.name
    end

    What's next