List topics

This document describes how to list a Pub/Sub topic. To list a topic you can use the Google Cloud console, the gcloud CLI, the client library, or the Pub/Sub API.

Before you begin

Required roles and permissions

To get the permissions that you need to list topics 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 topics 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 topics and manage them:

  • Create a topic: pubsub.topics.create
  • Delete a topic: pubsub.topics.delete
  • Detach a subscription from a topic: pubsub.topics.detachSubscription
  • Get a topic: pubsub.topics.get
  • List a topic: pubsub.topics.list
  • Publish to a topic: pubsub.topics.publish
  • Update a topic: pubsub.topics.update
  • Get the IAM policy for a topic: pubsub.topics.getIamPolicy
  • Configure the IAM policy for a topic: pubsub.topics.setIamPolicy

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

You can configure access control at the project level and at the individual resource level. You can create a subscription in one project and attach it to a topic located in a different project. Ensure that you have the required permissions for each project.

List a topic

Console

  • In the Google Cloud console, go to the Pub/Sub Topics page.

  • Go to Topics

    The Topics page lists all the available topics.

    By default, the console returns 50 topics. You can increase this value to return a maximum of 200 topics by using the Rows per page drop down toggle. This toggle only appears in the console if you have more than 20 topics in a project.

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 topics, use the gcloud pubsub topics list command:

    gcloud pubsub topics list

By default, a maximum of 100 results are returned per query. You can specify an alternative value of up to 1,000 using the page size parameter. For example, using the Google Cloud CLI, specify --page-size=1000.

REST

To list topics, use the projects.topics.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
Authorization: Bearer ACCESS_TOKEN
    

Where:

  • PROJECT_ID is your project ID.
  • Response:

    {
      "topics": [
        {
          "name": "projects/PROJECT_ID/topics/mytopic1",
          ...
        },
        {
          "name": "projects/PROJECT_ID/topics/mytopic2",
          ...
        }
      ]
    }
    

    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::TopicAdminClient client, std::string const& project_id) {
      int count = 0;
      for (auto& topic : client.ListTopics("projects/" + project_id)) {
        if (!topic) throw std::move(topic).status();
        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.

    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 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.

    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.Topic, 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 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: %w", 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.

    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.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

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

    Node.js

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

    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"
    
    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.

    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
    
    topics = pubsub.topics
    
    puts "Topics in project:"
    topics.each do |topic|
      puts topic.name
    end

    What's next