Simple "Hello world" samples for accessing Google Cloud APIs in (node,dotnet,java,golang,python)
Simple "Hello world" samples for accessing Google Cloud APIs in (node,dotnet,java,golang,python)
Sample code demonstrating various Auth mechanism for Google Cloud Platform APIs.
Please refer to official documentation for usage and additional samples/usage.
The samples use Application Default Credentials which uses credentials in the following order as described in the link. Set the environment variable to override.
You can always specify the target source to acquire credentials by using intent specific targets such as: ComputeCredentials, UserCredentials or ServiceAccountCredential.
There are two types of client libraries you can use to connect to Google APIs:
##### Using google.auth for GoogleAPIs
The following shows transport authorization for the original Google APIs
```python
import oauth2client
from oauth2client.client import GoogleCredentials
import httplib2
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default()
if credentials.create_scoped_required():
credentials = credentials.create_scoped(scopes)
http = credentials.authorize(http)If you need to use the more recent Google Cloud Auth library, you need to cast the transport:
import google.auth
import google_auth_httplib2
scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
credentials, project = google.auth.default(scopes=scopes)
http = google_auth_httplib2.AuthorizedHttp(credentials)or preferably init a cloud API:
from google.cloud import storage
import google.auth
from google.oauth2 import service_account
import os
#credentials = service_account.Credentials.from_service_account_file('YOUR_JSON_CERT.json')
#if credentials.requires_scopes:
# credentials = credentials.with_scopes(['https://www.googleapis.com/auth/devstorage.read_write'])
#client = storage.Client(credentials=credentials)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/svc_account.json"
credentials, project = google.auth.default()
client = storage.Client(credentials=credentials)
buckets = client.list_buckets()
for bkt in buckets:
print(bkt)If you want to enable trace logging with google-cloud-python* library set,
#!/usr/bin/python
from google.cloud import bigquery
from six.moves import http_client
http_client.HTTPConnection.debuglevel = 5
client = bigquery.Client()
query_job = client.query("""
SELECT timestamp
FROM
`your-project.gae_request_logs.appengine_googleapis_com_request_log_20161119`
ORDER BY timestamp DESC
LIMIT
4;""")
results = query_job.result()
for row in results:
print(row)
…
xml
com.google.cloud
google-cloud-storage
zzzz
com.google.cloud
google-cloud-pubsub
yyyy
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Blob.BlobSourceOption;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage.SignUrlOption;
import java.util.concurrent.TimeUnit;
import java.net.URL;
import java.util.Iterator;
import java.io.FileInputStream;
//import com.google.auth.oauth2.ServiceAccountCredentials;
// Using Google Cloud APIs with service account file
// You can also just export an export GOOGLE_APPLICATION_CREDENTIALS and use StorageOptions.defaultInstance().service()
// see https://github.com/google/google-auth-library-java#google-auth-library-oauth2-http
/*
Storage storage_service = StorageOptions.newBuilder()
.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream("/path/to/your/certificate.json")))
.build()
.getService();
*/
Storage storage_service = StorageOptions.newBuilder()
.build()
.getService();
for (Bucket b : storage_service.list().iterateAll()){
System.out.println(b);
}
// You can also use the client to generate a signed URL:
URL signedUrl = storage_service.signUrl(BlobInfo.newBuilder("your_project", "a.txt").build(), 60, TimeUnit.SECONDS);
System.out.println(signedUrl);see proxy/README.md
see Example
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.Binding;
import com.google.cloud.Role;
// setup topicadmin client using the bit above
TopicAdminClient topicClient =
TopicAdminClient.create(
TopicAdminSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(credentialsProvider)
.build());
String formattedResource = TopicName.create("your-project", "saltopic2").toString();
GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder()
.setResource(formattedResource)
.build();
ApiFuture future = topicAdminClient.getIamPolicyCallable().futureCall(request);
Policy response = future.get();
System.out.println(response);
Package cloud.google.com/go/storage
The following shows google.DefaultTokenSource as well as gcloud's Application Default Credentials
import (
"golang.org/x/net/context"
"cloud.google.com/go/storage"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"log"
)
ctx := context.Background()
/*
tokenSource, err := google.DefaultTokenSource(oauth2.NoContext, storage.ScopeReadOnly)
if err != nil {
log.Fatalf("Unable to acquire token source: %v", err)
}
storeageClient, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource))
*/
storeageClient, err := storage.NewClient(ctx)
if err != nil {
log.Fatalf("Unable to acquire storage Client: %v", err)
}
it := storeageClient.Buckets(ctx, "your_project")
for {
bucketAttrs, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Unable to acquire storage Client: %v", err)
}
log.Printf(bucketAttrs.Name)
}
package main
import (
"context"
"io/ioutil"
"log"
"net/http"
"cloud.google.com/go/storage"
"google.golang.org/api/option"
raw "google.golang.org/api/storage/v1"
htransport "google.golang.org/api/transport/http"
)
func main() {
ctx := context.Background()
// Standard way to initialize client:
// client, err := storage.NewClient(ctx)
// if err != nil {
// // handle error
// }
// Instead, create a custom http.Client.
base := http.DefaultTransport
trans, err := htransport.NewTransport(ctx, base, option.WithScopes(raw.DevstorageFullControlScope),
option.WithUserAgent("custom-user-agent"))
if err != nil {
// Handle error.
}
c := http.Client{Transport:trans}
// Add RoundTripper to the created HTTP client.
c.Transport = withDebugHeader{c.Transport}
// Supply this client to storage.NewClient
client, err := storage.NewClient(ctx, option.WithHTTPClient(&c))
if err != nil {
// Handle error.
}
// Use client...
}
type withDebugHeader struct {
rt http.RoundTripper
}
func (wdh withDebugHeader) RoundTrip(r *http.Request) (*http.Response, error) {
headerName := "X-Custom-Header"
r.Header.Add(headerName, "value")
resp, err := wdh.rt.RoundTrip(r)
if err == nil {
log.Printf("Resp Header: %+v, ", resp.Header.Get(headerName))
} else {
log.Printf("Error: %+v", err)
}
return resp, err
}
…
node
const Storage = require('@google-cloud/storage');
const storage = new Storage({
projectId: 'your-project',
});
storage.getBuckets(function(err, buckets) {
if (!err) {
buckets.forEach(function(value){
logger.info(value.id);
});
}
});
const Pubsub = require('@google-cloud/pubsub');
const pubsub = Pubsub({
projectId: 'your-project'
});
pubsub.getTopics((err, topic) => {
if (err) {
logger.error(err);
return;
}
topic.forEach(function(entry) {
logger.info(entry.name);
});
});Use Google.Cloud.Storage.V1 package for Google Cloud API access
See auth/service/dotnet for sample for both Cloud APIs and Google APIs libraries.
using Google.Cloud.Storage.V1;
namespace CloudStorageAppGcloud
{
class Program
{
static void Main(string[] args)
{
var client = StorageClient.Create();
foreach (var obj in client.ListObjects("your_project", ""))
{
Console.WriteLine(obj.Name);
}
Console.ReadLine();
}
}
}
JWT access tokens are efficient way to access certain google apis without the extra round trip to get an access_token. Unlike the normal Oauth service account flow where you
access_tokenaccess_token to make an API call to googlewith JWT Access Tokens, all you do is sign a JWT locally with a service account with the intended Service you want to access and then simply send it to the service.
The following links describes this flow:
where these Google APIs will support this:
eg. for PubSub
// https://github.com/googleapis/googleapis/blob/master/google/pubsub/pubsub.yaml#L6
ctx := context.Background()
projectID := "YOUR_PROJECT"
keyfile := "service_account.json"
audience := "https://pubsub.googleapis.com/google.pubsub.v1.Publisher"
keyBytes, err := ioutil.ReadFile(keyfile)
if err != nil {
log.Fatalf("Unable to read service account key file %v", err)
}
tokenSource, err := google.JWTAccessTokenSourceFromJSON(keyBytes, audience)
if err != nil {
log.Fatalf("Error building JWT access token source: %v", err)
}
jwt, err := tokenSource.Token()
if err != nil {
log.Fatalf("Unable to generate JWT token: %v", err)
}
fmt.Println(jwt.AccessToken)
pubsubClient, err := pubsub.NewClient(ctx, projectID, option.WithTokenSource(tokenNo open issues yet, or sync has not completed.