Cloud Pub/Sub Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Pub/Sub API.

Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library

C#

For more information, see Setting Up a C# Development Environment.
Install-Package Google.Cloud.PubSub.V1 -Pre

Go

go get -u cloud.google.com/go/pubsub

Java

For more information, see Setting Up a Java Development Environment. If you are using Maven, add this to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-pubsub</artifactId>
  <version>1.51.0</version>
</dependency>
If you are using Gradle, add this to your dependencies:
compile 'com.google.cloud:google-cloud-pubsub:1.51.0'
If you are using SBT, add this to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "1.51.0"

If you're using IntelliJ or Eclipse, you can add client libraries to your project using these IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/pubsub

PHP

composer require google/cloud-pubsub

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-pubsub

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-pubsub

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP Console

  1. In the GCP Console, go to the Create service account key page.

    Go to the Create Service Account Key page
  2. From the Service account drop-down list, select New service account.
  3. In the Service account name field, enter a name .
  4. From the Role drop-down list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or within Cloud Shell.

  1. Create the service account. Replace [NAME] with your desired service account name.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account. Replace [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

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

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

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static int Main(string[] args)
        {
            // Instantiates a client
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();

            // Your Google Cloud Platform project ID
            string projectId = "YOUR-PROJECT-ID";

            // The name for the new topic
            var topicName = new TopicName(projectId, "my-new-topic");

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

Go

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

If you're running on Google App Engine standard, we recommend using the older Google APIs Client Libraries. See this GitHub issue for more details.
// Sample pubsub-quickstart creates a Google Cloud Pub/Sub topic.
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	ctx := context.Background()

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the name for the new topic.
	topicName := "my-topic"

	// Creates the new topic.
	topic, err := client.CreateTopic(ctx, topicName)
	if err != nil {
		log.Fatalf("Failed to create topic: %v", err)
	}

	fmt.Printf("Topic %v created.\n", topic)
}

Java

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

// Imports the Google Cloud client library

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.ProjectTopicName;

public class CreateTopicExample {

  /**
   * Create a topic.
   *
   * @param args topicId
   * @throws Exception exception thrown if operation is unsuccessful
   */
  public static void main(String... args) throws Exception {

    // Your Google Cloud Platform project ID
    String projectId = ServiceOptions.getDefaultProjectId();

    // Your topic ID, eg. "my-topic"
    String topicId = args[0];

    // Create a new topic
    ProjectTopicName topic = ProjectTopicName.of(projectId, topicId);
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      topicAdminClient.createTopic(topic);
    } catch (ApiException e) {
      // example : code = ALREADY_EXISTS(409) implies topic already exists
      System.out.print(e.getStatusCode().getCode());
      System.out.print(e.isRetryable());
    }

    System.out.printf("Topic %s:%s created.\n", topic.getProject(), topic.getTopic());
  }
}

Node.js

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

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

async function quickstart() {
  // Your Google Cloud Platform project ID
  const projectId = process.env.GCLOUD_PROJECT || 'YOUR_PROJECT_ID';

  // Instantiates a client
  const pubsubClient = new PubSub({
    projectId: projectId,
  });

  // The name for the new topic
  const topicName = 'my-topic';

  // Creates the new topic
  const [topic] = await pubsubClient.createTopic(topicName);
  console.log(`Topic ${topic.name} created.`);
}
quickstart().catch(console.error);

PHP

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

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\PubSub\PubSubClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$pubsub = new PubSubClient([
    'projectId' => $projectId
]);

# The name for the new topic
$topicName = 'my-new-topic-2';

# Creates the new topic
$topic = $pubsub->createTopic($topicName);

echo 'Topic ' . $topic->name() . ' created.';

Python

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

from google.cloud import pubsub_v1

# TODO project_id = "Your Google Cloud Project ID"
# TODO topic_name = "Your Pub/Sub topic name"

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

topic = publisher.create_topic(topic_path)

print('Topic created: {}'.format(topic))

Ruby

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

# Imports the Google Cloud client library
require "google/cloud/pubsub"

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Instantiates a client
pubsub = Google::Cloud::Pubsub.new project: project_id

# The name for the new topic
topic_name = "my-new-topic"

# Creates the new topic
topic = pubsub.create_topic topic_name

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

Additional Resources

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Pub/Sub