Create and use topics

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

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.

Guidelines to name a topic or a subscription

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/ID

  • project-identifier. Must be the project ID, available from the Google Cloud console. For example, projects/sampleproject/topics/sampletopic.

  • collection. Must be one of subscriptions, snapshots, or topics.

  • ID. Must conform to the following guidelines:

    • 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 +, and percent signs %

    You can use the special characters in the preceding list in resource names without URL-encoding. However, you must ensure that any other special characters are properly encoded or decoded when you use them in URLs. For example, mi-tópico is an invalid relative-name. However, mi-t%C3%B3pico is valid. This format is important when you make REST calls.

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

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.

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

    # topic_id = "your-topic-id"
    require "google/cloud/pubsub"
    
    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

    Create a topic with a schema

    While creating a topic, you might want to assign it a schema.

    The following are some guidelines about using schemas:

    • You cannot add schemas to existing topics.
    • You can specify a schema only when you create a topic.
    • After a schema is associated with a topic, you cannot update the schema or remove its association with that topic.
    • You can apply the same schema to other new topics.
    • If you delete a schema, publishing to all associated topics fails.

    To know more about schemas, see Create and manage schemas.

    Console

    To create a topic and assign it a schema, follow these steps:

    1. In the 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. Check the box for Use a schema. Leave the other options in their default settings.

    5. Click Select a Pub/Sub schema and select Create a new schema. If you want to use an existing schema, skip to step 7.

    6. In the Schema ID field, enter an ID for your schema.

    7. For Schema type, select either Avro or Protocol Buffer.

    8. In the Schema definition field, enter the Avro of Protocol Buffer definition for your schema.

    9. Click Create to save the schema.

    10. In the Create a topic dialog window, search for your schema in the Select a Pub/Sub schema field.

    11. Click Create to save the topic and assign it with the selected schema.

    gcloud

    To create a topic assigned with a previously created schema, run the gcloud pubsub topics create command:

    gcloud pubsub topics create TOPIC_ID \
            --message-encoding=ENCODING_TYPE \
            --schema=SCHEMA_ID
    

    Where:

    • TOPIC_ID is the ID for the topic that you're creating.
    • ENCODING_TYPE is the encoding of messages validated against the schema. This value must be set to either JSON or BINARY.
    • SCHEMA_ID is the ID of an existing schema.

    You can also assign a schema from a different Google Cloud project:

    gcloud pubsub topics create TOPIC_ID \
            --message-encoding=ENCODING_TYPE \
            --schema=SCHEMA_ID \
            --schema-project=SCHEMA_PROJECT \
            --project=TOPIC_PROJECT
    

    Where:

    • SCHEMA_PROJECT is the project ID of the Google Cloud project for the schema.
    • TOPIC_PROJECT is the project ID of the Google Cloud project for the topic.

    REST

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

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

    Request body:

    {
      "schemaSettings": {
        "schema": "SCHEMA_NAME",
        "encoding": "ENCODING_TYPE"
      }
    }
    

    Where:

    • PROJECT_ID is your project ID.
    • TOPIC_ID is your topic ID.
    • SCHEMA_NAME is the name of the schema that messages published should be validated against. The format is: projects/PROJECT_ID/schemas/SCHEMA_ID.
    • ENCODING_TYPE is the encoding of messages validated against the schema. This must be set to either JSON or BINARY.

    Response:

    {
      "name": "projects/PROJECT_ID/topics/TOPIC_ID",
      "schemaSettings": {
        "schema": "SCHEMA_NAME",
        "encoding": "ENCODING_TYPE"
      }
    }
    

    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, std::string schema_id, std::string const& encoding) {
      auto const& schema = pubsub::Schema(project_id, std::move(schema_id));
      auto topic = client.CreateTopic(
          pubsub::TopicBuilder(
              pubsub::Topic(std::move(project_id), std::move(topic_id)))
              .set_schema(schema)
              .set_encoding(encoding == "JSON" ? google::pubsub::v1::JSON
                                               : google::pubsub::v1::BINARY));
      // 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 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 CreateTopicWithSchemaSample
    {
        public Topic CreateTopicWithSchema(string projectId, string topicId, string schemaName, Encoding encoding)
        {
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            var topicName = TopicName.FromProjectTopic(projectId, topicId);
            Topic topic = new Topic
            {
                Name = topicName.ToString(),
                SchemaSettings = new SchemaSettings
                {
                    Schema = schemaName,
                    Encoding = encoding
                }
            };
    
            Topic receivedTopic = null;
            try
            {
                receivedTopic = publisher.CreateTopic(topic);
                Console.WriteLine($"Topic {topic.Name} created.");
            }
            catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
            {
                Console.WriteLine($"Topic {topicName} already exists.");
            }
            return receivedTopic;
        }
    }

    Go

    Before trying this sample, follow the Go setup instructions in 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 createTopicWithSchema(w io.Writer, projectID, topicID, schemaID string, encoding pubsub.SchemaEncoding) error {
    	// projectID := "my-project-id"
    	// topicID := "my-topic"
    	// schemaID := "my-schema-id"
    	// encoding := pubsub.EncodingJSON
    	ctx := context.Background()
    	client, err := pubsub.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("pubsub.NewClient: %v", err)
    	}
    
    	tc := &pubsub.TopicConfig{
    		SchemaSettings: &pubsub.SchemaSettings{
    			Schema:   fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
    			Encoding: encoding,
    		},
    	}
    	t, err := client.CreateTopicWithConfig(ctx, topicID, tc)
    	if err != nil {
    		return fmt.Errorf("CreateTopicWithConfig: %v", err)
    	}
    	fmt.Fprintf(w, "Topic with schema created: %#v\n", t)
    	return nil
    }
    

    Java

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

    
    import com.google.api.gax.rpc.AlreadyExistsException;
    import com.google.cloud.pubsub.v1.TopicAdminClient;
    import com.google.pubsub.v1.Encoding;
    import com.google.pubsub.v1.SchemaName;
    import com.google.pubsub.v1.SchemaSettings;
    import com.google.pubsub.v1.Topic;
    import com.google.pubsub.v1.TopicName;
    import java.io.IOException;
    
    public class CreateTopicWithSchemaExample {
    
      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";
        // Use an existing schema.
        String schemaId = "your-schema-id";
        // Choose either BINARY or JSON message serialization in this topic.
        Encoding encoding = Encoding.BINARY;
    
        createTopicWithSchemaExample(projectId, topicId, schemaId, encoding);
      }
    
      public static void createTopicWithSchemaExample(
          String projectId, String topicId, String schemaId, Encoding encoding) throws IOException {
        TopicName topicName = TopicName.of(projectId, topicId);
        SchemaName schemaName = SchemaName.of(projectId, schemaId);
    
        SchemaSettings schemaSettings =
            SchemaSettings.newBuilder().setSchema(schemaName.toString()).setEncoding(encoding).build();
    
        try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
    
          Topic topic =
              topicAdminClient.createTopic(
                  Topic.newBuilder()
                      .setName(topicName.toString())
                      .setSchemaSettings(schemaSettings)
                      .build());
    
          System.out.println("Created topic with schema: " + topic.getName());
        } catch (AlreadyExistsException e) {
          System.out.println(schemaName + "already exists.");
        }
      }
    }

    Node.js

    Before trying this sample, follow the Node.js setup instructions in 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 topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
    // const schemaName = 'YOUR_SCHEMA_NAME_OR_ID';
    // const encodingType = 'BINARY';
    
    // 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 createTopicWithSchema(
      topicNameOrId,
      schemaNameOrId,
      encodingType
    ) {
      // Get the fully qualified schema name.
      const schema = pubSubClient.schema(schemaNameOrId);
      const fullName = await schema.getName();
    
      // Creates a new topic with a schema. Note that you might also
      // pass Encodings.Json or Encodings.Binary here.
      await pubSubClient.createTopic({
        name: topicNameOrId,
        schemaSettings: {
          schema: fullName,
          encoding: encodingType,
        },
      });
      console.log(`Topic ${topicNameOrId} created with schema ${fullName}.`);
    }

    PHP

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

    use Google\Cloud\PubSub\PubSubClient;
    use Google\Cloud\PubSub\Schema;
    
    /**
     * Create a topic with a schema.
     *
     * @param string $projectId
     * @param string $topicId
     * @param string $schemaId
     * @param string $encoding
     */
    function create_topic_with_schema($projectId, $topicId, $schemaId, $encoding)
    {
        $pubsub = new PubSubClient([
            'projectId' => $projectId,
        ]);
    
        $schema = $pubsub->schema($schemaId);
    
        $topic = $pubsub->createTopic($topicId, [
            'schemaSettings' => [
                // The schema may be provided as an instance of the schema type,
                // or by using the schema ID directly.
                'schema' => $schema,
                // Encoding may be either `BINARY` or `JSON`.
                // Provide a string or a constant from Google\Cloud\PubSub\V1\Encoding.
                'encoding' => $encoding,
            ]
        ]);
    
        printf('Topic %s created', $topic->name());
    }

    Python

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

    from google.api_core.exceptions import AlreadyExists, InvalidArgument
    from google.cloud.pubsub import PublisherClient, SchemaServiceClient
    from google.pubsub_v1.types import Encoding
    
    # TODO(developer): Replace these variables before running the sample.
    # project_id = "your-project-id"
    # topic_id = "your-topic-id"
    # schema_id = "your-schema-id"
    # Choose either BINARY or JSON as valid message encoding in this topic.
    # message_encoding = "BINARY"
    
    publisher_client = PublisherClient()
    topic_path = publisher_client.topic_path(project_id, topic_id)
    
    schema_client = SchemaServiceClient()
    schema_path = schema_client.schema_path(project_id, schema_id)
    
    if message_encoding == "BINARY":
        encoding = Encoding.BINARY
    elif message_encoding == "JSON":
        encoding = Encoding.JSON
    else:
        encoding = Encoding.ENCODING_UNSPECIFIED
    
    try:
        response = publisher_client.create_topic(
            request={
                "name": topic_path,
                "schema_settings": {"schema": schema_path, "encoding": encoding},
            }
        )
        print(f"Created a topic:\n{response}")
    
    except AlreadyExists:
        print(f"{topic_id} already exists.")
    except InvalidArgument:
        print("Please choose either BINARY or JSON as a valid message encoding type.")

    Ruby

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

    # topic_id = "your-topic-id"
    # schema_id = "your-schema-id"
    # Choose either BINARY or JSON as valid message encoding in this topic.
    # message_encoding = :binary
    require "google/cloud/pubsub"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic = pubsub.create_topic topic_id, schema_name: schema_id, message_encoding: message_encoding
    
    puts "Topic #{topic.name} created."

    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 topic with the same name as a topic you had just deleted, expect an error for a brief period.

    Console

    1. In the 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

    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.

    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)
    	}
    	defer client.Close()
    
    	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 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() {
      /**
       * 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.`);
    }
    
    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(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.

    # topic_id = "your-topic-id"
    require "google/cloud/pubsub"
    
    pubsub = Google::Cloud::Pubsub.new
    
    topic = pubsub.topic topic_id
    topic.delete
    
    puts "Topic #{topic_id} deleted."

    List a topic

    Console

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

      Go to Topics

      The Topics page lists all the available topics.

    gcloud

    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.

    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)
    	}
    	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: %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.

    What's next