Client: Create credentials with scopes

Create credentials with Drive and BigQuery API scopes.

Documentation pages that include this code sample

Code Sample

Java

Before trying this sample, follow the Java setup instructions in the BigQuery Quickstart Using Client Libraries. For more information, see the BigQuery Java API reference documentation.

import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;

public class AuthDriveScope {

  public static void main(String[] args) throws IOException {
    setAuthDriveScope();
  }

  public static void setAuthDriveScope() throws IOException {
    // Create credentials with Drive & BigQuery API scopes.
    // Both APIs must be enabled for your project before running this code.
    GoogleCredentials credentials =
        ServiceAccountCredentials.getApplicationDefault()
            .createScoped(
                ImmutableSet.of(
                    "https://www.googleapis.com/auth/bigquery",
                    "https://www.googleapis.com/auth/drive"));

    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery =
          BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();

      // Use the client.
      System.out.println("Auth succeeded with multiple scopes. Datasets:");
      for (Dataset dataset : bigquery.listDatasets().iterateAll()) {
        System.out.printf("Dataset: %s%n", dataset.getDatasetId().getDataset());
      }
    } catch (BigQueryException e) {
      System.out.println("Auth failed due to error: \n" + e.toString());
    }
  }
}

Python

Before trying this sample, follow the Python setup instructions in the BigQuery Quickstart Using Client Libraries. For more information, see the BigQuery Python API reference documentation.

from google.cloud import bigquery
import google.auth

# Create credentials with Drive & BigQuery API scopes.
# Both APIs must be enabled for your project before running this code.
credentials, project = google.auth.default(
    scopes=[
        "https://www.googleapis.com/auth/drive",
        "https://www.googleapis.com/auth/bigquery",
    ]
)

# Construct a BigQuery client object.
client = bigquery.Client(credentials=credentials, project=project)