This page shows how to get started with the Cloud Client Libraries for the
Pub/Sub API. Client libraries make it easier to access
Google Cloud APIs from a supported language. Although you can use
Google Cloud APIs directly by making raw requests to the server, client
libraries provide simplifications that significantly reduce the amount of code
you need to write.

<br />

> [!NOTE]
> **Note:** Instructions on this page apply to the Python 3 and Java 8 [App Engine standard environments](https://docs.cloud.google.com/appengine/docs/about-the-standard-environment). To use Python 2 with App Engine Standard, see [this sample](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/standard/pubsub).

Read more about the Cloud Client Libraries and the older Google API Client Libraries in [Client libraries explained](https://docs.cloud.google.com/apis/docs/client-libraries-explained.md.txt).

<br />

## Install the client library

### C++

For information about this client library's requirements and install
dependencies, see [Setting up a C++ development environment](https://docs.cloud.google.com/cpp/docs/setup.md.txt).


### C#

```
Install-Package Google.Cloud.PubSub.V1 -Pre
```

For more information, see [Setting Up a C# Development Environment](https://docs.cloud.google.com/dotnet/docs/setup.md.txt).

### Go

```
go get cloud.google.com/go/pubsub/v2
```

For more information, see [Setting Up a Go Development Environment](https://docs.cloud.google.com/go/docs/setup.md.txt).

### Java

If you are using [Maven](https://maven.apache.org/), add
the following to your `pom.xml` file. For more information about
BOMs, see [The Google Cloud Platform Libraries BOM](https://cloud.google.com/java/docs/bom).

```java
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.76.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-pubsub</artifactId>
  </dependency>

</dependencies>
```

If you are using [Gradle](https://gradle.org/),
add the following to your dependencies:

```java
implementation platform('com.google.cloud:libraries-bom:26.80.0')

implementation 'com.google.cloud:google-cloud-pubsub'
```

If you are using [sbt](https://www.scala-sbt.org/), add
the following to your dependencies:

```java
libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "1.150.2"
```

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your
project using the following IDE plugins:

- [Cloud Code for VS Code](https://docs.cloud.google.com/code/docs/vscode/client-libraries.md.txt)
- [Cloud Code for IntelliJ](https://docs.cloud.google.com/code/docs/intellij/client-libraries.md.txt)

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

> [!NOTE]
> **Note:** Cloud Java client libraries do not currently support Android.

For more information, see [Setting Up a Java Development Environment](https://docs.cloud.google.com/java/docs/setup.md.txt).

### Node.js

```
npm install @google-cloud/pubsub
```

For more information, see [Setting Up a Node.js Development Environment](https://docs.cloud.google.com/nodejs/docs/setup.md.txt).

### PHP

```
composer require google/cloud-pubsub
```

For more information, see [Using PHP on Google Cloud](https://docs.cloud.google.com/php/docs.md.txt).

### Python

```
pip install --upgrade google-cloud-pubsub
```

For more information, see [Setting Up a Python Development Environment](https://docs.cloud.google.com/python/docs/setup.md.txt).

### Ruby

```
gem install google-cloud-pubsub
```

For more information, see [Setting Up a Ruby Development Environment](https://docs.cloud.google.com/ruby/docs/setup.md.txt).

### Rust

```
cargo add google-cloud-pubsub
```

For more information, see [Get started with Rust](https://docs.cloud.google.com/rust/docs/quickstart.md.txt).

<br />

## Set up authentication

To authenticate calls to Google Cloud APIs, client libraries support [Application Default Credentials (ADC)](https://docs.cloud.google.com/docs/authentication/application-default-credentials.md.txt); the libraries look for credentials in a set of defined locations and use those credentials to authenticate requests to the API. With ADC, you can make credentials available to your application in a variety of environments, such as local development or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the service
and context. For more information, see [Set up Application Default Credentials](https://docs.cloud.google.com/docs/authentication/provide-credentials-adc.md.txt).

For a local development environment, you can set up ADC with the credentials
that are associated with your Google Account:

1.
   [Install](https://docs.cloud.google.com/sdk/docs/install) the Google Cloud CLI.

   After installation,
   [initialize](https://docs.cloud.google.com/sdk/docs/initializing) the Google Cloud CLI by running the following command:

   ```bash
   gcloud init
   ```


   If you're using an external identity provider (IdP), you must first
   [sign in to the gcloud CLI with your federated identity](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud.md.txt).
2.

   If you're using a local shell, then create local authentication credentials for your user
   account:

   ```bash
   gcloud auth application-default login
   ```

   You don't need to do this if you're using Cloud Shell.


   If an authentication error is returned, and you are using an external identity provider
   (IdP), confirm that you have
   [signed in to the gcloud CLI with your federated identity](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud.md.txt).


   A sign-in screen appears. After you sign in, your credentials are stored in the
   [local credential file used by ADC](https://docs.cloud.google.com/docs/authentication/application-default-credentials.md.txt#personal).

## Use the client library


The following example shows how to use the client library to
create a Pub/Sub topic.

### C++

```c++
namespace pubsub = ::google::cloud::pubsub;
namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::TopicAdminClient client, std::string project_id,
   std::string topic_id) {
  auto topic = client.CreateTopic(
      pubsub::Topic(std::move(project_id), std::move(topic_id)).FullName());
  // 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#

```c#

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

```go

// Sample pubsub-quickstart creates a Google Cloud Pub/Sub topic.
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/pubsub/v2"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

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)
	}
	defer client.Close()

	// Sets the id for the new topic.
	topicID := "my-topic"
	pbTopic := &pubsubpb.Topic{
		Name: fmt.Sprintf("projects/%s/topics/%s", projectID, topicID),
	}

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

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

### Java

```java

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

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

async function quickstart(
  projectId = 'your-project-id', // Your Google Cloud Platform project ID
  topicNameOrId = 'my-topic', // Name for the new topic to create
  subscriptionName = 'my-sub', // Name for the new subscription to create
) {
  // Instantiates a client
  const pubsub = new PubSub({projectId});

  // Creates a new topic
  const [topic] = await pubsub.createTopic(topicNameOrId);
  console.log(`Topic ${topic.name} created.`);

  // Creates a subscription on that new topic
  const [subscription] = await topic.createSubscription(subscriptionName);

  // Receive callbacks for new messages on the subscription
  subscription.on('message', message => {
    console.log('Received message:', message.data.toString());
    process.exit(0);
  });

  // Receive callbacks for errors on the subscription
  subscription.on('error', error => {
    console.error('Received error:', error);
    process.exit(1);
  });

  // Send a message to the topic
  await topic.publishMessage({data: Buffer.from('Test message!')});
}
```

### Python

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

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

# Instantiates a client
pubsub = Google::Cloud::PubSub.new
topic_admin = pubsub.topic_admin

# The name for the new topic
# topic_id = "your-topic-id"

# Creates the new topic
topic = topic_admin.create_topic name: pubsub.topic_path(topic_id)

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

### Rust

```rust
use google_cloud_pubsub::client::TopicAdmin;

pub async fn sample(client: &TopicAdmin, project_id: &str, topic_id: &str) -> anyhow::Result<()> {
    let topic = client
        .create_topic()
        .set_name(format!("projects/{project_id}/topics/{topic_id}"))
        .send()
        .await?;

    println!("successfully created topic {topic:?}");
    Ok(())
}
```

<br />

## Additional resources

### C++

The following list contains links to more resources related to the
client library for C++:

- [API reference](https://docs.cloud.google.com/cpp/docs/reference/pubsub/latest.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/google-cloud-cpp/issues?q=is:issue+api:+pubsub)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D%5Bc%2B%2B%5D)
- [Source code](https://github.com/googleapis/google-cloud-cpp/tree/main/google/cloud/pubsub)

### C#

The following list contains links to more resources related to the
client library for C#:

- [API reference](https://docs.cloud.google.com/dotnet/docs/reference/Google.Cloud.PubSub.V1/latest.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/google-cloud-dotnet/issues?q=is:issue+api:+pubsub)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bc%23%5D)
- [Source code](https://github.com/googleapis/google-cloud-dotnet/tree/main/apis/Google.Cloud.PubSub.V1)

### Go

The following list contains links to more resources related to the
client library for Go:

- [API reference](https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/pubsub/latest.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/google-cloud-go/issues)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bgo%5D)
- [Source code](https://github.com/googleapis/google-cloud-go)

### Java

The following list contains links to more resources related to the
client library for Java:

- [API reference](https://docs.cloud.google.com/java/docs/reference/google-cloud-pubsub/latest/overview.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/java-pubsub/issues)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bjava%5D)
- [Source code](https://github.com/googleapis/java-pubsub)

### Node.js

The following list contains links to more resources related to the
client library for Node.js:

- [API reference](https://docs.cloud.google.com/nodejs/docs/reference/pubsub/latest.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/nodejs-pubsub/issues)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bnode.js%5D)
- [Source code](https://github.com/googleapis/nodejs-pubsub)

### PHP

The following list contains links to more resources related to the
client library for PHP:

- [API reference](https://googleapis.github.io/google-cloud-php/#/docs/cloud-pubsub/latest/pubsub/pubsubclient)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/google-cloud-php/issues?q=is:issue+api:+pubsub+)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bphp%5D)
- [Source code](https://github.com/googleapis/google-cloud-php/tree/main/PubSub)

### Python

The following list contains links to more resources related to the
client library for Python:

- [API reference](https://docs.cloud.google.com/python/docs/reference/pubsub/latest.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/python-pubsub/issues)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bpython%5D)
- [Source code](https://github.com/googleapis/python-pubsub)

### Ruby

The following list contains links to more resources related to the
client library for Ruby:

- [API reference](https://docs.cloud.google.com/ruby/docs/reference/google-cloud-pubsub/latest.md.txt)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/google-cloud-ruby/issues?q=is:issue+api:+pubsub+)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Bruby%5D)
- [Source code](https://github.com/googleapis/google-cloud-ruby/tree/main/google-cloud-pubsub)

### Rust

The following list contains links to more resources related to the
client library for Rust:

- [API reference](https://docs.rs/google-cloud-pubsub)
- [Client libraries best practices](https://docs.cloud.google.com/apis/docs/client-libraries-best-practices.md.txt)
- [Issue tracker](https://github.com/googleapis/google-cloud-rust/issues?q=is:issue+label:%22api:+pubsub%22)
- [`google-cloud-pubsub` on Stack Overflow](https://stackoverflow.com/search?q=%5Bgoogle-cloud-pubsub%5D+%5Brust%5D)
- [Source code](https://github.com/googleapis/google-cloud-rust/tree/main/src/pubsub)

<br />


## Additional Pub/Sub API libraries

| Language | Library |
|---|---|
| Java | [java-pubsub-group-kafka-connector](https://github.com/googleapis/java-pubsub-group-kafka-connector) |

<br />