Create a client with a service account key file

Create a BigQuery client using a service account key file.

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.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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.

To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

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());
  }
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.