Pub/Sub client libraries
Stay organized with collections
Save and categorize content based on your preferences.
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.
Read more about the Cloud Client Libraries
and the older Google API Client Libraries
in Client libraries explained.
To authenticate calls to Google Cloud APIs, client libraries support
Application Default Credentials (ADC);
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.
For a local development environment, you can set up ADC with the credentials
that are associated with your Google Account:
Install the Google Cloud CLI.
After installation,
initialize the Google Cloud CLI by running the following command:
The following example shows how to use the client library to
create a Pub/Sub topic.
C++
namespacepubsub=::google::cloud::pubsub;namespacepubsub_admin=::google::cloud::pubsub_admin;[](pubsub_admin::TopicAdminClientclient,std::stringproject_id,std::stringtopic_id){autotopic=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)throwstd::move(topic).status();std::cout << "The topic was successfully created: " << topic->DebugString() << "\n";}
// Sample pubsub-quickstart creates a Google Cloud Pub/Sub topic.packagemainimport("context""fmt""log""cloud.google.com/go/pubsub/v2""cloud.google.com/go/pubsub/v2/apiv1/pubsubpb")funcmain(){ctx:=context.Background()// Sets your Google Cloud Platform project ID.projectID:="YOUR_PROJECT_ID"// Creates a client.client,err:=pubsub.NewClient(ctx,projectID)iferr!=nil{log.Fatalf("Failed to create client: %v",err)}deferclient.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)iferr!=nil{log.Fatalf("Failed to create topic: %v",err)}fmt.Printf("Topic %v created.\n",topic)}
Java
importcom.google.cloud.pubsub.v1.TopicAdminClient;importcom.google.pubsub.v1.Topic;importcom.google.pubsub.v1.TopicName;importjava.io.IOException;publicclassCreateTopicExample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringtopicId="your-topic-id";createTopicExample(projectId,topicId);}publicstaticvoidcreateTopicExample(StringprojectId,StringtopicId)throwsIOException{try(TopicAdminClienttopicAdminClient=TopicAdminClient.create()){TopicNametopicName=TopicName.of(projectId,topicId);Topictopic=topicAdminClient.createTopic(topicName);System.out.println("Created topic: "+topic.getName());}}}
Node.js
// Imports the Google Cloud client libraryconst{PubSub}=require('@google-cloud/pubsub');asyncfunctionquickstart(projectId='your-project-id',// Your Google Cloud Platform project IDtopicNameOrId='my-topic',// Name for the new topic to createsubscriptionName='my-sub',// Name for the new subscription to create){// Instantiates a clientconstpubsub=newPubSub({projectId});// Creates a new topicconst[topic]=awaitpubsub.createTopic(topicNameOrId);console.log(`Topic ${topic.name} created.`);// Creates a subscription on that new topicconst[subscription]=awaittopic.createSubscription(subscriptionName);// Receive callbacks for new messages on the subscriptionsubscription.on('message',message=>{console.log('Received message:',message.data.toString());process.exit(0);});// Receive callbacks for errors on the subscriptionsubscription.on('error',error=>{console.error('Received error:',error);process.exit(1);});// Send a message to the topicawaittopic.publishMessage({data:Buffer.from('Test message!')});}
# Imports the Google Cloud client libraryrequire"google/cloud/pubsub"# Instantiates a clientpubsub=Google::Cloud::PubSub.newtopic_admin=pubsub.topic_admin# The name for the new topic# topic_id = "your-topic-id"# Creates the new topictopic=topic_admin.create_topicname:pubsub.topic_path(topic_id)puts"Topic #{topic.name} created."
Additional resources
C++
The following list contains links to more resources related to the
client library for C++:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-06-09 UTC."],[],[]]