Authenticating With a Service Account Key File

Manually create and obtain service account credentials to use BigQuery when an application is deployed on-premises or to other public clouds. You can set the environment variable to load the credentials using Application Default Credentials, or you can specify the path to load the credentials manually in your application code.

This guide will show you how to load the credentials from a file.

Before you begin

Loading credentials from a file

Create credentials in your application from the service account file. Then use the credentials to create a service object with the BigQuery Client Libraries.

Java

Create a ServiceAccountCredentials object from a file using ServiceAccountCredentials.fromStream(InputStream). Pass the credentials to a BigQueryOptions.Builder and create the BigQuery service from those options.

public static void explicit() throws IOException {
  // Load credentials from JSON key file. If you can't set the GOOGLE_APPLICATION_CREDENTIALS
  // environment variable, you can explicitly load the credentials file to construct the
  // credentials.
  GoogleCredentials credentials;
  File credentialsPath = new File("service_account.json");  // TODO: update to your key path.
  try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
    credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
  }

  // Instantiate a client.
  BigQuery bigquery =
      BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();

  // Use the client.
  System.out.println("Datasets:");
  for (Dataset dataset : bigquery.listDatasets().iterateAll()) {
    System.out.printf("%s%n", dataset.getDatasetId().getDataset());
  }
}

Python

Use bigquery.Client.from_service_account_json(path) to create a BigQuery Client using the service account key file.

def explicit():
    from google.cloud import bigquery

    # Explicitly use service account credentials by specifying the private key
    # file. All clients in google-cloud-python have this helper, see
    # https://google-cloud-python.readthedocs.io/en/latest/core/modules.html
    #   #google.cloud.client.Client.from_service_account_json
    bigquery_client = bigquery.Client.from_service_account_json(
        'service_account.json')

    # Make an authenticated API request
    buckets = list(bigquery_client.list_datasets())
    print(buckets)

What's next

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...