Create an assignment to map a project, folder, or organization to a BigQuery reservation.

## Code sample

### Java


Before trying this sample, follow the Java setup instructions in the
[BigQuery quickstart using
client libraries](https://docs.cloud.google.com/bigquery/docs/quickstarts/quickstart-client-libraries).


For more information, see the
[BigQuery Java API
reference documentation](https://docs.cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/overview).


To authenticate to BigQuery, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/bigquery/docs/authentication#client-libs).

    import com.google.api.gax.rpc.https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.AlreadyExistsException.html;
    import com.google.api.gax.rpc.https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ApiException.html;
    import com.google.cloud.bigquery.reservation.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.html;
    import com.google.cloud.bigquery.reservation.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.html;
    import com.google.cloud.bigquery.reservation.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationName.html;
    import com.google.cloud.bigquery.reservation.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationServiceClient.html;
    import java.io.IOException;

    public class CreateAssignment {

      /**
       * Creates a new assignment for a BigQuery reservation so a project can run jobs of a specified
       * type using slots from that reservation.
       *
       * @param projectId The Google Cloud project ID of the reservation owner (for example,
       *     "example-project-id").
       * @param location The geographic location of the reservation (for example, "us-central1").
       * @param reservationId The ID of the reservation to create the assignment in (for example,
       *     "example-reservation").
       */
      public static void createAssignment(String projectId, String location, String reservationId) {
        https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationName.html parent = https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationName.html.of(projectId, location, reservationId);
        String assignee = String.format("projects/%s", projectId);

        https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.html assignment =
            https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.html.newBuilder()
                .https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.Builder.html#com_google_cloud_bigquery_reservation_v1_Assignment_Builder_setAssignee_java_lang_String_(assignee)
                .https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.Builder.html#com_google_cloud_bigquery_reservation_v1_Assignment_Builder_setJobType_com_google_cloud_bigquery_reservation_v1_Assignment_JobType_(https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.html.JobType.QUERY)
                .build();

        https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.html request =
            https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.CreateAssignmentRequest.html.newBuilder()
                .setParent(parent.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationName.html#com_google_cloud_bigquery_reservation_v1_ReservationName_toString__())
                .setAssignment(assignment)
                .build();

        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationServiceClient.html client = https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.ReservationServiceClient.html.create()) {
          https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.html createdAssignment = client.createAssignment(request);
          System.out.printf("Created assignment: %s%n", createdAssignment.https://docs.cloud.google.com/java/docs/reference/google-cloud-bigqueryreservation/latest/com.google.cloud.bigquery.reservation.v1.Assignment.html#com_google_cloud_bigquery_reservation_v1_Assignment_getName__());
        } catch (https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.AlreadyExistsException.html err) {
          System.err.printf(
              "error: assignment for project '%s' and job type QUERY already exists in reservation '%s': %s%n",
              projectId, reservationId, err.https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ErrorDetails.html#com_google_api_gax_rpc_ErrorDetails__T_getMessage_java_lang_Class_T__());
        } catch (https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ApiException.html | IOException err) {
          System.err.printf(
              "error: failed to create assignment in reservation '%s' for project '%s': %s%n",
              reservationId, projectId, err.https://docs.cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.rpc.ErrorDetails.html#com_google_api_gax_rpc_ErrorDetails__T_getMessage_java_lang_Class_T__());
        }
      }

### Node.js


Before trying this sample, follow the Node.js setup instructions in the
[BigQuery quickstart using
client libraries](https://docs.cloud.google.com/bigquery/docs/quickstarts/quickstart-client-libraries).


For more information, see the
[BigQuery Node.js API
reference documentation](https://googleapis.dev/nodejs/bigquery/latest/index.html).


To authenticate to BigQuery, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/bigquery/docs/authentication#client-libs).

    const {
      ReservationServiceClient,
    } = require('https://docs.cloud.google.com/nodejs/docs/reference/bigquery-reservation/latest/overview.html').v1;
    const {status} = require('@grpc/grpc-js');

    const client = new https://docs.cloud.google.com/nodejs/docs/reference/bigquery-reservation/latest/overview.html();

    /**
     * Creates an assignment to assign a project to a reservation.
     * A reservation assignment lets a project submit jobs of a certain type
     * using slots from the specified reservation.
     *
     * @param {string} projectId Google Cloud Project ID that owns the reservation, for example 'example-project-id'.
     * @param {string} location Google Cloud Location, for example 'us-central1'.
     * @param {string} reservationId The ID of the reservation to which the project will be assigned, for example 'example-reservation'.
     */
    async function createAssignment(
      projectId,
      location = 'us-central1',
      reservationId = 'example-reservation',
    ) {
      const parent = client.https://docs.cloud.google.com/nodejs/docs/reference/bigquery-reservation/latest/bigquery-reservation/v1.reservationserviceclient.html(projectId, location, reservationId);
      const request = {
        parent,
        assignment: {
          assignee: `projects/${projectId}`,
          jobType: 'https://docs.cloud.google.com/nodejs/docs/reference/bigquery-reservation/latest/bigquery-reservation/protos.google.cloud.bigquery.reservation.v1.assignment.jobtype.html',
        },
      };

      try {
        const [assignment] = await client.createAssignment(request);
        console.log(`Created assignment: ${assignment.name}`);
        console.log(`  Assignee: ${assignment.assignee}`);
        console.log(`  Job Type: ${assignment.jobType}`);
      } catch (err) {
        if (err.code === status.ALREADY_EXISTS) {
          console.log(
            `Assignment for project ${projectId} to reservation ${reservationId} already exists.`,
          );
        } else {
          console.error('Error creating assignment:', err);
        }
      }
    }

### Python


Before trying this sample, follow the Python setup instructions in the
[BigQuery quickstart using
client libraries](https://docs.cloud.google.com/bigquery/docs/quickstarts/quickstart-client-libraries).


For more information, see the
[BigQuery Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/bigquery/latest).


To authenticate to BigQuery, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/bigquery/docs/authentication#client-libs).

    from google.api_core import exceptions
    from google.cloud import https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest

    client = https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest.https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest/google.cloud.bigquery_reservation_v1.services.reservation_service.ReservationServiceClient.html()


    def create_assignment(project_id: str, location: str, reservation_id: str):
        """Creates a new assignment for a reservation.

        This shows how to create an assignment that gives a project access to
        a reservation.

        Args:
            project_id: The Google Cloud project ID of the reservation owner.
            location: The geographic location of the reservation, for example, "US".
            reservation_id: The ID of the reservation to create the assignment in.
        """

        parent = client.https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest/google.cloud.bigquery_reservation_v1.services.reservation_service.ReservationServiceClient.html#google_cloud_bigquery_reservation_v1_services_reservation_service_ReservationServiceClient_reservation_path(project_id, location, reservation_id)
        assignee = f"projects/{project_id}"
        assignment = https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest.https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest/google.cloud.bigquery_reservation_v1.types.Assignment.html(
            assignee=assignee,
            job_type=https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest.https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest/google.cloud.bigquery_reservation_v1.types.Assignment.html.https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest/google.cloud.bigquery_reservation_v1.types.Assignment.JobType.html.QUERY,
        )

        try:
            created_assignment = client.https://docs.cloud.google.com/python/docs/reference/bigqueryreservation/latest/google.cloud.bigquery_reservation_v1.services.reservation_service.ReservationServiceClient.html#google_cloud_bigquery_reservation_v1_services_reservation_service_ReservationServiceClient_create_assignment(
                parent=parent, assignment=assignment
            )
            print(f"Created assignment: {created_assignment.name}")
        except exceptions.AlreadyExists:
            print(f"Assignment for project {project_id} and job type QUERY already exists.")

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=bigquery).