Create and manage topics

Within Pub/Sub, a topic is a named resource that represents a feed of messages.

This document explains how to create, update, view, and delete a Pub/Sub topic. This document also explains how to name topics and subscriptions.

Data replication in a topic

A Pub/Sub topic uses three zones to store data. The service guarantees synchronous replication to at least two zones, and best-effort replication to an additional third zone. Pub/Sub replication is within just one region.

Properties of a topic

When you create or update a topic, you must specify its properties.

  • Add a default subscription. Adds a default subscription to the Pub/Sub topic. You can create another subscription for the topic after the topic is created. The default subscription has the following properties:

    • Subscription ID of -sub
    • Pull delivery type
    • Message retention duration of seven days
    • Expiration after 31 days of inactivity
    • Acknowledgment deadline of 10 seconds
    • Immediate retry policy
  • Schema. A schema is a format that the message data field must follow. A schema is a contract between the publisher and subscriber that Pub/Sub enforces. Topic schemas help standardize message types and permissions to allow them to be consumed by different teams in your organization. Pub/Sub creates a central authority for message types and permissions. To create a topic with schema, see Create and manage schemas.

  • Message retention duration. Specifies how long the Pub/Sub topic retains messages after publication. After the message retention duration is over, Pub/Sub might discard the message regardless of its acknowledgment state. Message storage fees are charged for storing all messages published to the topic.

    • Default = Not enabled
    • Minimum value = 10 minutes
    • Maximum value = 31 days
  • Use a customer-managed encryption key (CMEK). Specifies if the topic is encrypted with a CMEK. Pub/Sub encrypts messages with Google-managed keys by default. If you specify this option, Pub/Sub uses the envelope encryption pattern with CMEK. In this approach, Cloud KMS does not encrypt the messages. Instead, Cloud KMS encrypts the Data Encryption Keys (DEKs) that Pub/Sub creates for each topic. Pub/Sub encrypts the messages using the newest DEK that was generated for the topic. Pub/Sub decrypts the messages shortly before they are delivered to subscribers. For more information about creating a key, see Configure message encryption.

Required roles and permissions to manage topics

To get the permissions that you need to create and manage topics, 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.

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

Required permissions

The following permissions are required to create and manage topics:

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

Create a topic

Create a topic before you can publish or subscribe to it.

Console

To create a topic, follow these steps:

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

    Go to Topics

  2. Click Create topic.

  3. In the Topic ID field, enter an ID for your topic.

  4. Retain the option Add a default subscription.

  5. Do not select the other options.

  6. Click Create 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 create a topic, run the gcloud pubsub topics create command:

    gcloud pubsub topics create TOPIC_ID

REST

To create a topic, use the projects.topics.create method:

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

Where:

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

    {
     "name": "projects/PROJECT_ID/topics/TOPIC_ID"
    }
    

    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 = ::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::move(topic).status();
    
      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.

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

    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"
    	"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: %w", err)
    	}
    	defer client.Close()
    
    	t, err := client.CreateTopic(ctx, topicID)
    	if err != nil {
    		return fmt.Errorf("CreateTopic: %w", 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.

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

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

    /**
     * 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 createTopic(topicNameOrId) {
      // Creates a new topic
      await pubSubClient.createTopic(topicNameOrId);
      console.log(`Topic ${topicNameOrId} created.`);
    }

    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;
    
    /**
     * 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.

    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)
    
    topic = publisher.create_topic(request={"name": topic_path})
    
    print(f"Created topic: {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.

    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.create_topic topic_id
    
    puts "Topic #{topic.name} created."

    Organization policy constraints

    Organizational policies can restrict topic creation, for example, a policy can restrict message storage in a Compute Engine region. To avoid topic creation errors, examine and update organizational policies, as needed, before creating a topic.

    If your project is newly created, wait a few minutes for the organization policy to initialize before creating a topic.

    Go to Organization Policies

    Delete a topic

    When you delete a topic, its subscriptions are not deleted. The message backlog from the subscription is available for subscribers. After a topic is deleted, its subscriptions have the topic name _deleted-topic_. If you try to create a Pub/Sub resource with the same name and type of resource you had just deleted, expect an error for a brief period.

    Console

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

      Go to Topics

    2. Select a topic and click More actions.

    3. Click Delete.

      The Delete topic window appears.

    4. Enter delete and then click Delete.

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

      gcloud pubsub topics delete TOPIC_ID

    REST

    To delete a topic, use the projects.topics.delete 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.

    DELETE https://pubsub.googleapis.com/v1/projects/PROJECT_ID/topics/TOPIC_ID
    Authorization: Bearer ACCESS_TOKEN
        

    Where:

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

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

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

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

    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"
    	"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: %w", err)
    	}
    	defer client.Close()
    
    	t := client.Topic(topicID)
    	if err := t.Delete(ctx); err != nil {
    		return fmt.Errorf("Delete: %w", 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.

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

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

    /**
     * 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 deleteTopic(topicNameOrId) {
      /**
       * TODO(developer): Uncomment the following line to run the sample.
       */
      // const topicName = 'my-topic';
    
      // Deletes the topic
      await pubSubClient.topic(topicNameOrId).delete();
      console.log(`Topic ${topicNameOrId} deleted.`);
    }

    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;
    
    /**
     * 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.

    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)
    
    publisher.delete_topic(request={"topic": topic_path})
    
    print(f"Topic deleted: {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.

    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
    topic.delete
    
    puts "Topic #{topic_id} deleted."

    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.

    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

    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 = ::google::cloud::pubsub;
    [](pubsub::TopicAdminClient client, std::string const& project_id) {
      int count = 0;
      for (auto& topic : client.ListTopics(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

    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.

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

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

    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

    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.

    Monitor topics

    You can monitor topics from within Pub/Sub.

    What's next