Create a new data exchange in Analytics Hub.

## Code sample

### Go


Before trying this sample, follow the Go 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 Go API
reference documentation](https://godoc.org/cloud.google.com/go/bigquery).


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.md.txt#client-libs).

```go

import (
	"context"
	"fmt"
	"io"

	analyticshub "cloud.google.com/go/bigquery/analyticshub/apiv1"
	analyticshubpb "cloud.google.com/go/bigquery/analyticshub/apiv1/analyticshubpb"
)

// createDataExchange creates a new data exchange in Analytics Hub.
func createDataExchange(ctx context.Context, w io.Writer, dataExchangeID string, projectID string, locationID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	dataExchange := &analyticshubpb.DataExchange{
		DisplayName: "Example Data Exchange",
		Description: "Data exchange created for analytics demonstration.",
	}

	client, err := analyticshub.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("analyticshub.NewClient: %w", err)
	}
	defer client.Close()

	req := &analyticshubpb.CreateDataExchangeRequest{
		Parent:         parent,
		DataExchangeId: dataExchangeID,
		DataExchange:   dataExchange,
	}

	resp, err := client.CreateDataExchange(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateDataExchange: %w", err)
	}

	fmt.Fprintf(w, "Created data exchange: %s\n", resp.GetName())
	return nil
}
```

### 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.md.txt#client-libs).

```java
import com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubServiceClient;
import com.google.cloud.bigquery.analyticshub.v1.CreateDataExchangeRequest;
import com.google.cloud.bigquery.analyticshub.v1.DataExchange;
import java.io.IOException;

public class CreateDataExchange {

  public static void main(String[] args) throws IOException {
    String dataExchangeId = "example_data_exchange_id";
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    createDataExchange(dataExchangeId, projectId, locationId);
  }

  public static void createDataExchange(String dataExchangeId, String projectId, String locationId)
      throws IOException {
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      DataExchange dataExchange =
          DataExchange.newBuilder()
              .setDisplayName("Example Data Exchange")
              .setDescription("Example description")
              .build();
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);

      CreateDataExchangeRequest request =
          CreateDataExchangeRequest.newBuilder()
              .setParent(parent)
              .setDataExchangeId(dataExchangeId)
              .setDataExchange(dataExchange)
              .build();

      DataExchange response = client.createDataExchange(request);
      System.out.println("Data exchange created successfully: " + response.getName());
    }
  }
}
```

### 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.md.txt#client-libs).

```javascript
'use strict';

const {AnalyticsHubServiceClient} = require('@google-cloud/bigquery-analyticshub');
const {status} = require('@grpc/grpc-js');

const client = new AnalyticsHubServiceClient();

/**
 * Use the createDataExchange method
 *
 * @param {string} dataExchangeId - ID of the data exchange to create. Must contain only letters, numbers, and underscores (e.g., 'example_data_exchange'). Max length: 100 bytes.
 * @param {string} projectId - Google Cloud project ID where the data exchange will be created.
 * @param {string} locationId - Geographic location of the data exchange (e.g., 'us' or 'us-central1').
 */
async function createDataExchange(dataExchangeId, projectId, locationId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const dataExchange = {
      displayName: 'Example Data Exchange',
      description: 'Analytics Hub data exchange for dataset sharing',
    };

    const request = {
      parent,
      dataExchangeId,
      dataExchange,
    };

    const [response] = await client.createDataExchange(request);
    console.log(`Created data exchange: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Data exchange already exists: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else {
      console.error(`Failed to create data exchange: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { createDataExchange };
```

### 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.md.txt#client-libs).

```python
import google.api_core.exceptions
from google.cloud import bigquery_analyticshub_v1


def create_data_exchange(
    data_exchange_id: str, project_id: str, location_id: str
) -> None:
    """Creates a data exchange in Analytics Hub.

    Args:
        data_exchange_id: The identifier for the data exchange.
        project_id: The Google Cloud project ID.
        location_id: The Google Cloud region or location for the data exchange,
          for example 'us' or 'us-central1'.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    parent = f"projects/{project_id}/locations/{location_id}"
    data_exchange = bigquery_analyticshub_v1.DataExchange(
        display_name="Sample Data Exchange",
        description="Data exchange created for analytics sharing",
    )

    request = bigquery_analyticshub_v1.CreateDataExchangeRequest(
        parent=parent,
        data_exchange_id=data_exchange_id,
        data_exchange=data_exchange,
    )

    try:
        response = client.create_data_exchange(request=request)
        print(f"Created data exchange: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Error creating data exchange: {error}")

```

## 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.md.txt?product=bigquery).