Create a client with a service account key file

Create a BigQuery client using a service account key file.

Documentation pages that include this code sample

Code Sample

C#

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

var credentials = GoogleCredential.FromFile(jsonPath);
var client = BigQueryClient.Create(projectId, credentials);

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.

public static void explicit() throws IOException {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "MY_PROJECT_ID";
  File credentialsPath = new File("path/to/your/service_account.json");

  // 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;
  try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) {
    credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
  }

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

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

Node.js

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

// Create a BigQuery client explicitly using service account credentials.
// by specifying the private key file.
const {BigQuery} = require('@google-cloud/bigquery');

const options = {
  keyFilename: 'path/to/service_account.json',
  projectId: 'my_project',
};

const bigquery = new BigQuery(options);

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
from google.oauth2 import service_account

# TODO(developer): Set key_path to the path to the service account key
#                  file.
# key_path = "path/to/service_account.json"

credentials = service_account.Credentials.from_service_account_file(
    key_path, scopes=["https://www.googleapis.com/auth/cloud-platform"],
)

client = bigquery.Client(credentials=credentials, project=credentials.project_id,)