Comparing Cloud Client vs GoogleAPI Libraries

2021-12-21

This section juxtaposes the two types of client libraries described in Google Client libraries explained

This does not go into any more details than describe in the linked documentation page but it does show the difference in the library at least in basic constructors and idiomatic use. In other words, use this to help understand cosmetic usability differences between the set and appreciate the convenience of the Cloud Client Library which is the preferred mechanism.

There are occasional usecases for the Google API clients where you may need to manipulate the low-level constructors and initializers or when a Cloud Client Library has not been generated yet. THese usecases should be rare and encouragement is again to migrate to the Client Library set.

The following snippets shows at a per language level the iteration of Cloud Storage Buckets and PubSub Topics

Cloud Client Library

TODO

project='mineral-minutia-820'

from google.cloud import storage
client = storage.Client(project=project)
for b in client.list_buckets():
   print(b.name)

from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
project_path = f"projects/{project}"
for topic in publisher.list_topics(request={"project": project_path}):
  print(topic.name)
package main

import (
	"fmt"

	pubsub "cloud.google.com/go/pubsub"
	storage "cloud.google.com/go/storage"
	"golang.org/x/net/context"
	"google.golang.org/api/iterator"
)

const (
	projectID = "mineral-minutia-820"
)

func main() {

	ctx := context.Background()

	storageClient, err := storage.NewClient(ctx)
	if err != nil {
		fmt.Printf("storage.NewClient: %v", err)
		return
	}
	defer storageClient.Close()

	it := storageClient.Buckets(ctx, projectID)
	for {
		battrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			fmt.Printf("storage.Iterating error: %v", err)
			return
		}
		fmt.Printf("Bucket Name: %s\n", battrs.Name)
	}

	// *******************************************
	pubsubClient, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		fmt.Printf("pubsub.NewClient: %v", err)
		return
	}
	defer pubsubClient.Close()

	pit := pubsubClient.Topics(ctx)
	for {
		topic, err := pit.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			fmt.Printf("pubssub.Iterating error: %v", err)
			return
		}
		fmt.Printf("Topic Name: %s\n", topic.ID())
	}
}
package com.test;

import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.cloud.pubsub.v1.TopicAdminClient.ListTopicsPagedResponse;
import com.google.cloud.pubsub.v1.TopicAdminSettings;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.pubsub.v1.ListTopicsRequest;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Topic;

public class TestApp {
	public static void main(String[] args) {
		TestApp tc = new TestApp();
	}

	public TestApp() {
		try {

			Storage storage_service = StorageOptions.newBuilder().build().getService();
			for (Bucket b : storage_service.list().iterateAll()) {
				System.out.println(b);
			}

			TopicAdminClient topicClient = TopicAdminClient.create(TopicAdminSettings.newBuilder().build());

			ListTopicsRequest listTopicsRequest = ListTopicsRequest.newBuilder()
					.setProject(ProjectName.format("mineral-minutia-820"))
					.build();

			ListTopicsPagedResponse response = topicClient.listTopics(listTopicsRequest);
			Iterable<Topic> topics = response.iterateAll();
			for (Topic topic : topics)
				System.out.println(topic);

		} catch (Exception ex) {
			System.out.println("Error:  " + ex);
		}
	}

}
var log4js = require("log4js");
var logger = log4js.getLogger();

const {PubSub} = require('@google-cloud/pubsub');
const {Storage} = require('@google-cloud/storage');

var gcs = new Storage();
gcs.getBuckets(function(err, buckets) {
  if (!err) {
  	buckets.forEach(function(value){
  			logger.info(value.id);
	});
  }
});

const pubsub = new PubSub({
  projectId: 'mineral-minutia-820'
});
pubsub.getTopics((err, topic) => {
	if (err) {
		logger.error(err);
		return;
	}
	topic.forEach(function(entry) {
    logger.info(entry.name);
	});
});
using System;

using Google.Cloud.Storage.V1;
using Google.Cloud.PubSub.V1;
using System.Threading.Tasks;

using Google.Api.Gax.ResourceNames;

namespace main
{
    class Program
    {
        const string projectID = "mineral-minutia-820";
        [STAThread]
        static void Main(string[] args)
        {
            new Program().Run().Wait();
        }

        private Task Run()
        {
            var client = StorageClient.Create();
            foreach (var b in client.ListBuckets(projectID))
                Console.WriteLine(b.Name);

            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            ProjectName projectName = ProjectName.FromProject(projectID);
            foreach (Topic t in publisher.ListTopics(projectName))
                Console.WriteLine(t.TopicName);
            return Task.CompletedTask;
        }
    }
}

Google API Client Libraries

project='mineral-minutia-820'

from googleapiclient.discovery import build

storage_service = build('storage', 'v1')
req = storage_service.buckets().list(project=project)

while req:
   resp = req.execute()
   buckets = resp.get('items', [])
   for bucket in buckets:
      print(bucket['name'])
   req = storage_service.buckets().list_next(req, resp)
storage_service.close()


pubsub_service = build('pubsub', 'v1')
req = pubsub_service.projects().topics().list(project='projects/{}'.format(project))
while req:
   resp = req.execute()
   topics = resp.get('topics', [])
   for topic in topics:
      print(topic['name'])
   req = pubsub_service.projects().topics().list_next(req, resp)
pubsub_service.close()
package main

import (
	"fmt"

	"golang.org/x/net/context"

	"golang.org/x/oauth2/google"
	"google.golang.org/api/option"
	pubsub "google.golang.org/api/pubsub/v1"
	storage "google.golang.org/api/storage/v1"
)

const (
	projectID = "mineral-minutia-820"
)

func main() {

	ctx := context.Background()

	tokensrc, err := google.DefaultTokenSource(ctx, storage.CloudPlatformScope)
	if err != nil {
		fmt.Printf("Unable to acquire token source: %v", err)
		return
	}
	storageService, err := storage.NewService(ctx, option.WithTokenSource(tokensrc))
	if err != nil {
		fmt.Printf("Unable to create StorageService: %v", err)
		return
	}
	bucketList := storageService.Buckets.List(projectID)
	buckets, err := bucketList.Do()
	if err != nil {
		fmt.Printf("Unable to iterate buckets: %v", err)
		return
	}
	for _, bkt := range buckets.Items {
		fmt.Printf("Bucket Name: %s\n", bkt.Name)
	}

	// ****************

	pubsubService, err := pubsub.NewService(ctx, option.WithTokenSource(tokensrc))
	if err != nil {
		fmt.Printf("Unable to create pubsubService: %v", err)
		return
	}
	topicsList := pubsubService.Projects.Topics.List(fmt.Sprintf("projects/%s", projectID))
	topics, err := topicsList.Do()
	if err != nil {
		fmt.Printf("Unable to iterate topics: %v", err)
		return
	}
	for _, topic := range topics.Topics {
		fmt.Printf("Topic Name: %s\n", topic.Name)
	}
}
package com.test;

import java.util.Arrays;

import com.google.api.client.googleapis.util.Utils;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.services.pubsub.Pubsub;
import com.google.api.services.pubsub.model.ListTopicsResponse;
import com.google.api.services.pubsub.model.Topic;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.StorageScopes;
import com.google.api.services.storage.model.Bucket;
import com.google.api.services.storage.model.Buckets;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;

public class TestApp {
	public static void main(String[] args) {
		TestApp tc = new TestApp();
	}

	public TestApp() {
		try {
			String projectID = "mineral-minutia-820";
			GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();

			HttpTransport httpTransport = Utils.getDefaultTransport();
			JsonFactory jsonFactory = Utils.getDefaultJsonFactory();

			HttpRequestInitializer initializer = new HttpCredentialsAdapter(credentials);
			if (credentials.createScopedRequired())
				credentials = credentials.createScoped(Arrays.asList(StorageScopes.CLOUD_PLATFORM));

			Storage storageService = new Storage.Builder(httpTransport, jsonFactory, initializer)
					.setApplicationName("oauth client")
					.build();
			Buckets buckets = storageService.buckets().list(projectID).execute();
			System.out.println(buckets);

			for (Bucket b : buckets.getItems()) {
				System.out.println(b.getName());
			}

			// ****************

			Pubsub pubsubService = new Pubsub.Builder(httpTransport, jsonFactory, initializer)
					.setApplicationName("oauth client")
					.build();
			ListTopicsResponse listTopicsResponse = pubsubService.projects().topics().list("projects/" + projectID)
					.execute();
			for (Topic topic : listTopicsResponse.getTopics()) {
				System.out.println(topic.getName());

			}

			for (Bucket b : buckets.getItems()) {
				System.out.println(b.getName());
			}

		} catch (Exception ex) {
			System.out.println("Error:  " + ex);
		}
	}
}
var log4js = require("log4js");
var logger = log4js.getLogger();

const { google } = require('googleapis');
var { GoogleAuth } = require('google-auth-library');

const storage = google.storage('v1');
const pubsub = google.pubsub('v1');

async function main() {
	const auth = new google.auth.GoogleAuth({
		scopes: ['https://www.googleapis.com/auth/cloud-platform']
	});
	const authClient = await auth.getClient();
	const project = await auth.getProjectId();

	const buckets = await storage.buckets.list({ project, auth: authClient });
	buckets.data.items.forEach((bucket) => console.log(bucket.name));


	///  

	const projectName = `projects/${project}`;
	const topics = await pubsub.projects.topics.list({ project: projectName, auth: authClient });
	topics.data.topics.forEach((topic) => console.log(topic.name));

}

main().catch(console.error);
using System;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Storage.v1;
using Google.Apis.Storage.v1.Data;
using Google.Apis.Pubsub.v1;
using Google.Apis.Pubsub.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Google.Api.Gax.ResourceNames;

namespace main
{
    class Program
    {
        const string projectID = "mineral-minutia-820";
        [STAThread]
        static void Main(string[] args)
        {
            new Program().Run().Wait();
        }

        private Task Run()
        {
            var projectID = "mineral-minutia-820";

            GoogleCredential credential = GoogleCredential.GetApplicationDefault();
            var storageService = new StorageService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "testclient",
            });

            var request = new BucketsResource.ListRequest(storageService, projectID);
            var requestResult = request.Execute();
            foreach (var bucket in requestResult.Items)
            {
                Console.WriteLine(bucket.Name);
            }

            ///
            var pubsubService = new PubsubService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "testclient",
            });

            var prequest = new Google.Apis.Pubsub.v1.ProjectsResource.TopicsResource.ListRequest(pubsubService, "projects/" + projectID);
            var prequestResult = prequest.Execute();
            foreach (var topic in prequestResult.Topics)
            {
                Console.WriteLine(topic.Name);
            }
            return Task.CompletedTask;
        }
    }
}

This site supports webmentions. Send me a mention via this form.