BigQuery Reservation API Client Libraries

This page shows how to get started with the Cloud Client Libraries for the BigQuery Reservation API. Read more about the client libraries for Cloud APIs, including the older Google API Client Libraries, in Client Libraries Explained.

Installing the client library

Go

For more information, see Setting Up a Go Development Environment.

go get -u cloud.google.com/go/bigquery

Java

For more information, see Setting Up a Java Development Environment.

Si usas Maven, agrega lo siguiente al archivo pom.xml. Para obtener más información sobre las BOM, consulta Las bibliotecas de BOM de Google Cloud Platform.

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-bigqueryreservation</artifactId>
  <version>1.2.2</version>
</dependency>

Si usas Gradle, agrega lo siguiente a las dependencias:

compile 'com.google.cloud:google-cloud-bigqueryreservation:1.2.2'

Si usas sbt, agrega lo siguiente a las dependencias:

libraryDependencies += "com.google.cloud" % "google-cloud-bigqueryreservation" % "1.2.2"

Si usas Visual Studio Code, IntelliJ o Eclipse, puedes agregar bibliotecas cliente a tu proyecto con los siguientes complementos IDE:

Los complementos brindan funcionalidades adicionales, como administración de claves para las cuentas de servicio. Consulta la documentación de cada complemento para obtener más detalles.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install @google-cloud/bigquery-reservation

Python

For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-bigquery-reservation

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

Crea una cuenta de servicio:

  1. En Cloud Console, ve a la página Crear cuenta de servicio.

    Ir a Crear cuenta de servicio
  2. Selecciona un proyecto
  3. Ingresa un nombre en el campo Nombre de cuenta de servicio. Cloud Console completa el campo ID de cuenta de servicio con este nombre.

    En el campo Descripción de la cuenta de servicio, ingresa una descripción. Por ejemplo, Service account for quickstart.

  4. Haga clic en Crear.
  5. Haz clic en el campo Seleccionar una función.

    En Acceso rápido, haz clic en Básica y, luego, en Propietario.

  6. Haga clic en Continuar.
  7. Haz clic en Listo para terminar de crear la cuenta de servicio.

    No cierres la ventana del navegador. La usarás en la próxima tarea.

Para crear una clave de cuenta de servicio, haz lo siguiente:

  1. En Cloud Console, haz clic en la dirección de correo electrónico de la cuenta de servicio que creaste.
  2. Haz clic en Claves.
  3. Haz clic en Agregar clave y, luego, en Crear clave nueva.
  4. Haga clic en Crear. Se descargará un archivo de claves JSON a tu computadora.
  5. Haga clic en Cerrar.

Línea de comandos

Puedes ejecutar los siguientes comandos con el SDK de Cloud en tu máquina local o en Cloud Shell.

  1. Crea la cuenta de servicio. Reemplaza NAME por un nombre para la cuenta de servicio.

    gcloud iam service-accounts create NAME
  2. Otorga permisos a la cuenta de servicio. Reemplaza PROJECT_ID por el ID del proyecto.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Genera el archivo de claves. Reemplaza FILE_NAME por un nombre para el archivo de claves.

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=NAME@PROJECT_ID.iam.gserviceaccount.com

Configura la variable de entorno GOOGLE_APPLICATION_CREDENTIALS para proporcionar credenciales de autenticación al código de la aplicación. Esta variable solo se aplica a la sesión actual de shell. Por lo tanto, si abres una sesión nueva, deberás volver a configurar la variable.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta de acceso del archivo JSON que contiene la clave de tu cuenta de servicio.

Por ejemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta de acceso del archivo JSON que contiene la clave de tu cuenta de servicio.

Por ejemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Para el símbolo del sistema:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Reemplaza KEY_PATH por la ruta de acceso del archivo JSON que contiene la clave de tu cuenta de servicio.

Using the client library

The following example demonstrates some basic interactions with the BigQuery Reservation API by enumerating resources, namely reservations and capacity commitments.

Go

To use this sample, prepare your machine for Go development, and complete the BigQuery Reservation API quickstart. For more information, see the BigQuery Reservation API Go API reference documentation.


// The bigquery_reservation_quickstart application demonstrates usage of the
// BigQuery reservation API by enumerating some of the resources that can be
// associated with a cloud project.
package main

import (
	"bytes"
	"context"
	"flag"
	"fmt"
	"log"

	reservation "cloud.google.com/go/bigquery/reservation/apiv1"
	"google.golang.org/api/iterator"
	reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1"
)

func main() {

	// Define two command line flags for controlling the behavior of this quickstart.
	var (
		projectID = flag.String("project_id", "", "Cloud Project ID, used for session creation.")
		location  = flag.String("location", "US", "BigQuery location used for interactions.")
	)
	// Parse flags and do some minimal validation.
	flag.Parse()
	if *projectID == "" {
		log.Fatal("empty --project_id specified, please provide a valid project ID")
	}
	if *location == "" {
		log.Fatal("empty --location specified, please provide a valid location")
	}

	ctx := context.Background()
	bqResClient, err := reservation.NewClient(ctx)
	if err != nil {
		log.Fatalf("NewClient: %v", err)
	}
	defer bqResClient.Close()

	s, err := reportCapacityCommitments(ctx, bqResClient, *projectID, *location)
	if err != nil {
		log.Fatalf("printCapacityCommitments: %v", err)
	}
	fmt.Println(s)

	s, err = reportReservations(ctx, bqResClient, *projectID, *location)
	if err != nil {
		log.Fatalf("printReservations: %v", err)
	}
	fmt.Println(s)
}

// printCapacityCommitments iterates through the capacity commitments and returns a byte buffer with details.
func reportCapacityCommitments(ctx context.Context, client *reservation.Client, projectID, location string) (string, error) {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "Capacity commitments in project %s in location %s:\n", projectID, location)

	req := &reservationpb.ListCapacityCommitmentsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}
	totalCommitments := 0
	it := client.ListCapacityCommitments(ctx, req)
	for {
		commitment, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return "", err
		}
		fmt.Fprintf(&buf, "\tCommitment %s in state %s\n", commitment.GetName(), commitment.GetState().String())
		totalCommitments++
	}
	fmt.Fprintf(&buf, "\n%d commitments processed.\n", totalCommitments)
	return buf.String(), nil
}

// printReservations iterates through reservations defined in an admin project.
func reportReservations(ctx context.Context, client *reservation.Client, projectID, location string) (string, error) {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "Reservations in project %s in location %s:\n", projectID, location)

	req := &reservationpb.ListReservationsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}
	totalReservations := 0
	it := client.ListReservations(ctx, req)
	for {
		reservation, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return "", err
		}
		fmt.Fprintf(&buf, "\tReservation %s has %d slot capacity.\n", reservation.GetName(), reservation.GetSlotCapacity())
		totalReservations++
	}
	fmt.Fprintf(&buf, "\n%d reservations processed.\n", totalReservations)
	return buf.String(), nil
}

Java

Before trying this sample, follow the Java setup instructions in Setting up a Java development environment. For more information, see the BigQuery Reservation API Java API reference documentation.

import com.google.cloud.bigquery.reservation.v1.ReservationServiceClient;
import java.io.IOException;

public class QuickstartSample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String location = "LOCATION";
    quickStartSample(projectId, location);
  }

  public static void quickStartSample(String projectId, String location) throws IOException {
    try (ReservationServiceClient client = ReservationServiceClient.create()) {
      // list reservations in the project
      String parent = String.format("projects/%s/locations/%s", projectId, location);
      client
          .listReservations(parent)
          .iterateAll()
          .forEach(res -> System.out.println("Reservation resource name: " + res.getName()));

      // list capacity commitments in the project
      client
          .listCapacityCommitments(parent)
          .iterateAll()
          .forEach(
              commitment ->
                  System.out.println("Capacity commitment resource name: " + commitment.getName()));
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in Setting up a Node.js development environment. For more information, see the BigQuery Reservation API Node.js API reference documentation.

// Imports the Google Cloud client library
const {
  ReservationServiceClient,
} = require('@google-cloud/bigquery-reservation');

// Creates a client
const client = new ReservationServiceClient();

// project = 'my-project' // Project to list reservations for.
// location = 'US' // BigQuery location.

async function listReservations() {
  const [reservations] = await client.listReservations({
    parent: `projects/${project}/locations/${location}`,
  });

  console.info(`found ${reservations.length} reservations`);
  console.info(reservations);
}

async function listCapacityCommitments() {
  const [commitments] = await client.listCapacityCommitments({
    parent: `projects/${project}/locations/${location}`,
  });

  console.info(`found ${commitments.length} commitments`);
  console.info(commitments);
}

listReservations();
listCapacityCommitments();

Python

Before trying this sample, follow the Python setup instructions in Setting up a Python development environment. For more information, see the BigQuery Reservation API Python API reference documentation.

import argparse

from google.cloud import bigquery_reservation_v1


def main(project_id: str = "your-project-id", location: str = "US") -> None:
    # Constructs the client for interacting with the service.
    client = bigquery_reservation_v1.ReservationServiceClient()

    report_capacity_commitments(client, project_id, location)
    report_reservations(client, project_id, location)


def report_capacity_commitments(
    client: bigquery_reservation_v1.ReservationServiceClient,
    project_id: str,
    location: str,
) -> None:
    """Prints details and summary information about capacity commitments for
    a given admin project and location.
    """
    print(f"Capacity commitments in project {project_id} in location {location}")
    req = bigquery_reservation_v1.ListCapacityCommitmentsRequest(
        parent=client.common_location_path(project_id, location)
    )
    total_commitments = 0
    for commitment in client.list_capacity_commitments(request=req):
        print(f"\tCommitment {commitment.name} in state {commitment.state}")
        total_commitments = total_commitments + 1
    print(f"\n{total_commitments} commitments processed.")


def report_reservations(
    client: bigquery_reservation_v1.ReservationServiceClient,
    project_id: str,
    location: str,
) -> None:
    """Prints details and summary information about reservations defined within
    a given admin project and location.
    """
    print("Reservations in project {} in location {}".format(project_id, location))
    req = bigquery_reservation_v1.ListReservationsRequest(
        parent=client.common_location_path(project_id, location)
    )
    total_reservations = 0
    for reservation in client.list_reservations(request=req):
        print(
            f"\tReservation {reservation.name} "
            f"has {reservation.slot_capacity} slot capacity."
        )
        total_reservations = total_reservations + 1
    print(f"\n{total_reservations} reservations processed.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--project_id", type=str)
    parser.add_argument("--location", default="US", type=str)
    args = parser.parse_args()
    main(project_id=args.project_id, location=args.location)

Additional resources

What's next?

For more background and conceptual information about reservations, see Introduction to Reservations.