List subscriptions
Stay organized with collections
Save and categorize content based on your preferences.
You can list the subscriptions in a Google Cloud project with the Google Cloud console, Google Cloud CLI, client library, or Pub/Sub API.
Before you begin
- Learn about subscriptions.
- Create one of the following subscriptions, pull, push, or BigQuery.
Required roles and permissions
To get the permissions that
you need to list subscriptions,
ask your administrator to grant you the
Pub/Sub Editor (roles/pubsub.editor) IAM role on the project.
For more information about granting roles, see Manage access to projects, folders, and organizations.
This predefined role contains the permissions required to list subscriptions. To see the exact permissions that are required, expand the Required permissions section:
Required permissions
The following permissions are required to list subscriptions:
-
List subscriptions in a project:
pubsub.subscriptions.liston the project -
List subscriptions in a topic:
pubsub.topics.geton the topic
You might also be able to get these permissions with custom roles or other predefined roles.
List the subscriptions in a project
You can list the subscriptions in a Google Cloud project with the Google Cloud console, Google Cloud CLI, client library, or Pub/Sub API.
Console
To list the subscriptions in a project, go to the Subscriptions page.
Your subscriptions are listed in the table on the page.
gcloud
-
In the Google Cloud console, 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.
-
To list the subscriptions in a Google Cloud project, run the
gcloud pubsub subscriptions listcommand:gcloudpubsubsubscriptionslist[--project=PROJECT_ID]
REST
To list subscriptions in a project, use the
projects.subscriptions.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/subscriptions Authorization: Bearer ACCESS_TOKEN
Where:
- PROJECT_ID is your project ID.
Response:
{
"subscriptions": [
{
"name": "projects/PROJECT_ID/topics/mysubscription1",
"topic": "projects/PROJECT_ID/topics/TOPIC_ID",
"pushConfig": {},
"ackDeadlineSeconds": 10,
"retainAckedMessages": true,
"messageRetentionDuration": "604800s",
"expirationPolicy": {}
},
{
"name": "projects/PROJECT_ID/topics/mysubscription2",
"topic": "projects/PROJECT_ID/topics/TOPIC_ID",
"pushConfig": {
"pushEndpoint": "https://PROJECT_ID.appspot.com/myhandler",
"attributes": {
"x-goog-version": "v1"
}
},
"ackDeadlineSeconds": 10,
"retainAckedMessages": true,
"messageRetentionDuration": "604800s",
"expirationPolicy": {}
}
]
}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.
namespacepubsub_admin=::google::cloud::pubsub_admin;
[](pubsub_admin::SubscriptionAdminClientclient,
std::stringconst&project_id){
intcount=0;
google::pubsub::v1::ListSubscriptionsRequestrequest;
request.set_project(google::cloud::Project(project_id).FullName());
for(auto&subscription:client.ListSubscriptions(request)){
if(!subscription)throwstd::move(subscription).status();
std::cout << "Subscription Name: " << subscription->name() << "\n";
++count;
}
if(count==0){
std::cout << "No subscriptions found in project " << project_id << "\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.
usingGoogle.Api.Gax.ResourceNames ;
usingGoogle.Cloud.PubSub.V1 ;
usingSystem.Collections.Generic;
publicclassListSubscriptionsSample
{
publicIEnumerable<Subscription>ListSubscriptions(stringprojectId)
{
SubscriberServiceApiClient subscriber=SubscriberServiceApiClient .Create ();
ProjectName projectName=ProjectName .FromProject (projectId);
varsubscriptions=subscriber.ListSubscriptions (projectName);
returnsubscriptions;
}
}Go
The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2. To see a list of v1 code samples, see the deprecated code samples.
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"
"cloud.google.com/go/pubsub/v2"
"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
"google.golang.org/api/iterator"
)
funclist(projectIDstring)([]*pubsubpb.Subscription,error){
// projectID := "my-project-id"
ctx:=context.Background()
client,err:=pubsub.NewClient(ctx,projectID)
iferr!=nil{
returnnil,fmt.Errorf("pubsub.NewClient: %w",err)
}
deferclient.Close()
varsubs[]*pubsubpb.Subscription
req:=&pubsubpb.ListSubscriptionsRequest{
Project:fmt.Sprintf("projects/%s",projectID),
}
it:=client.SubscriptionAdminClient.ListSubscriptions(ctx,req)
for{
s,err:=it.Next()
iferr==iterator.Done{
break
}
iferr!=nil{
returnnil,fmt.Errorf("Next: %w",err)
}
subs=append(subs,s)
}
returnsubs,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.
importcom.google.cloud.pubsub.v1.SubscriptionAdminClient ;
importcom.google.pubsub.v1.ProjectName ;
importcom.google.pubsub.v1.Subscription ;
importjava.io.IOException;
publicclass ListSubscriptionsInProjectExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringprojectId="your-project-id";
listSubscriptionInProjectExample(projectId);
}
publicstaticvoidlistSubscriptionInProjectExample(StringprojectId)throwsIOException{
try(SubscriptionAdminClient subscriptionAdminClient=SubscriptionAdminClient .create()){
ProjectName projectName=ProjectName .of(projectId);
for(Subscription subscription:
subscriptionAdminClient.listSubscriptions(projectName).iterateAll()){
System.out.println(subscription.getName());
}
System.out.println("Listed all the subscriptions in the project.");
}
}
}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.
//ImportstheGoogleCloudclientlibrary
const{PubSub}=require('@google-cloud/pubsub');
//Createsaclient;cachethisforfurtheruse
constpubSubClient=newPubSub();
asyncfunctionlistSubscriptions(){
//Listsallsubscriptionsinthecurrentproject
const[subscriptions]=awaitpubSubClient.getSubscriptions();
console.log('Subscriptions:');
subscriptions.forEach(subscription=>console.log(subscription.name));
}Node.ts
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.
// Imports the Google Cloud client library
import{PubSub, Subscription} from'@google-cloud/pubsub';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function listSubscriptions() {
// Lists all subscriptions in the current project
const [subscriptions] = await pubSubClient.getSubscriptions();
console.log('Subscriptions:');
subscriptions.forEach((subscription: Subscription) =>
console.log(subscription.name),
);
}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;
/**
* Lists all Pub/Sub subscriptions.
*
* @param string $projectId The Google project ID.
*/
function list_subscriptions($projectId)
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
foreach ($pubsub->subscriptions() as $subscription) {
printf('Subscription: %s' . PHP_EOL, $subscription->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.
fromgoogle.cloudimport pubsub_v1
# TODO(developer)
# project_id = "your-project-id"
subscriber = pubsub_v1.SubscriberClient ()
project_path = f"projects/{project_id}"
# Wrap the subscriber in a 'with' block to automatically call close() to
# close the underlying gRPC channel when done.
with subscriber:
for subscription in subscriber.list_subscriptions(
request={"project": project_path}
):
print(subscription.name)Ruby
The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3. To see a list of Ruby v2 code samples, see the deprecated code samples.
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.
pubsub=Google::Cloud::PubSub .new
subscription_admin=pubsub.subscription_admin
subscriptions=subscription_admin.list_subscriptions\
project:pubsub.project_path
puts"Subscriptions:"
subscriptions.eachdo|subscription|
putssubscription.name
endList subscriptions to a topic
You can list the subscriptions to a topic with the Google Cloud console, Google Cloud CLI, or Pub/Sub API.
Console
- In the Google Cloud console, go to the Topics page.
- Select a topic ID to open the Topic details page. The Subscriptions section of the page includes a list of subscriptions to the topic.
gcloud
-
In the Google Cloud console, 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.
-
To list the subscriptions in a Google Cloud project, run the
gcloud pubsub topics list-subscriptionscommand:gcloudpubsubtopicslist-subscriptionsTOPIC_ID
REST
To list subscriptions in a topic, use the
projects.subscriptions.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/TOPIC_ID/subscriptions Authorization: Bearer ACCESS_TOKEN
Where:
- PROJECT_ID is your project ID.
- TOPIC_ID is your topic ID.
Response:
{
"subscriptions": [
"projects/PROJECT_ID/subscriptions/mysubscription1",
"projects/PROJECT_ID/subscriptions/mysubscription2"
]
}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.
namespacepubsub_admin=::google::cloud::pubsub_admin;
namespacepubsub=::google::cloud::pubsub;
[](pubsub_admin::TopicAdminClientclient,std::stringconst&project_id,
std::stringconst&topic_id){
autoconsttopic=pubsub::Topic(project_id,topic_id);
std::cout << "Subscription list for topic " << topic << ":\n";
for(auto&name:client.ListTopicSubscriptions(topic.FullName())){
if(!name)throwstd::move(name).status();
std::cout << " " << *name << "\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.
usingGoogle.Cloud.PubSub.V1 ;
usingSystem.Collections.Generic;
publicclassListSubscriptionsInTopicSample
{
publicIEnumerable<string>ListSubscriptionsInTopic(stringprojectId,stringtopicId)
{
PublisherServiceApiClient publisher=PublisherServiceApiClient .Create ();
TopicName topicName=TopicName .FromProjectTopic (projectId,topicId);
IEnumerable<string>subscriptions=publisher.ListTopicSubscriptions (topicName);
returnsubscriptions;
}
}Go
The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, see the migration guide to v2. To see a list of v1 code samples, see the deprecated code samples.
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/v2"
"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
"google.golang.org/api/iterator"
)
funclistSubscriptions(wio.Writer,projectID,topicIDstring)error{
// projectID := "my-project-id"
// topicName := "projects/sample-248520/topics/ocr-go-test-topic"
ctx:=context.Background()
client,err:=pubsub.NewClient(ctx,projectID)
iferr!=nil{
returnfmt.Errorf("pubsub.NewClient: %w",err)
}
deferclient.Close()
req:=&pubsubpb.ListTopicSubscriptionsRequest{
Topic:fmt.Sprintf("projects/%s/topics/%s",projectID,topicID),
}
it:=client.TopicAdminClient.ListTopicSubscriptions(ctx,req)
for{
sub,err:=it.Next()
iferr==iterator.Done{
break
}
iferr!=nil{
returnfmt.Errorf("error listing topic subscriptions: %w",err)
}
fmt.Fprintf(w,"got subscription: %s\n",sub)
}
returnnil
}
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.
importcom.google.cloud.pubsub.v1.TopicAdminClient ;
importcom.google.pubsub.v1.TopicName ;
importjava.io.IOException;
publicclass ListSubscriptionsInTopicExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringprojectId="your-project-id";
StringtopicId="your-topic-id";
listSubscriptionInTopicExample(projectId,topicId);
}
publicstaticvoidlistSubscriptionInTopicExample(StringprojectId,StringtopicId)
throwsIOException{
try(TopicAdminClient topicAdminClient=TopicAdminClient .create()){
TopicName topicName=TopicName .of(projectId,topicId);
for(Stringsubscription:topicAdminClient.listTopicSubscriptions(topicName).iterateAll()){
System.out.println(subscription);
}
System.out.println("Listed all the subscriptions in the topic.");
}
}
}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 this variable before running the sample.
*/
//consttopicNameOrId='YOUR_TOPIC_NAME_OR_ID';
//ImportstheGoogleCloudclientlibrary
const{PubSub}=require('@google-cloud/pubsub');
//Createsaclient;cachethisforfurtheruse
constpubSubClient=newPubSub();
asyncfunctionlistTopicSubscriptions(topicNameOrId){
//Listsallsubscriptionsforthetopic
const[subscriptions]=awaitpubSubClient
.topic(topicNameOrId)
.getSubscriptions();
console.log(`Subscriptionsfor${topicNameOrId}:`);
subscriptions.forEach(subscription=>console.log(subscription.name));
}Node.ts
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 this variable before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// Imports the Google Cloud client library
import{PubSub, Subscription} from'@google-cloud/pubsub';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function listTopicSubscriptions(topicNameOrId: string) {
// Lists all subscriptions for the topic
const [subscriptions] = await pubSubClient
.topic(topicNameOrId)
.getSubscriptions();
console.log(`Subscriptions for ${topicNameOrId}:`);
subscriptions.forEach((subscription: Subscription) =>
console.log(subscription.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.
fromgoogle.cloudimport 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)
response = publisher.list_topic_subscriptions(request={"topic": topic_path})
for subscription in response:
print(subscription)Ruby
The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3. To see a list of Ruby v2 code samples, see the deprecated code samples.
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"
pubsub=Google::Cloud::PubSub .new
topic_admin=pubsub.topic_admin
response=topic_admin.list_topic_subscriptions\
topic:pubsub.topic_path(topic_id)
puts"Subscriptions in topic #{topic_id}:"
response.subscriptions.eachdo|subscription_name|
putssubscription_name
endWhat's next
- Create or modify a subscription with
gcloudcommands. - Create or modify a subscription with REST APIs.