Create a listing within a data exchange to share a BigQuery dataset.

## 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"
)

// createListing creates a listing within a Data Exchange to share a BigQuery dataset.
func createListing(ctx context.Context, w io.Writer, listingID string, projectID string, locationID string, dataExchangeID string, datasetID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, locationID, dataExchangeID)
	listing := &analyticshubpb.Listing{
		DisplayName: "Example Listing",
		Description: "Listing created to share dataset resources",
		Source: &analyticshubpb.Listing_BigqueryDataset{
			BigqueryDataset: &analyticshubpb.Listing_BigQueryDatasetSource{
				Dataset: fmt.Sprintf("projects/%s/datasets/%s", projectID, datasetID),
			},
		},
	}

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

	req := &analyticshubpb.CreateListingRequest{
		Parent:    parent,
		ListingId: listingID,
		Listing:   listing,
	}

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

	fmt.Fprintf(w, "Created listing: %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.CreateListingRequest;
import com.google.cloud.bigquery.analyticshub.v1.Listing;
import java.io.IOException;

public class CreateListing {

  public static void main(String[] args) throws IOException {
    String listingId = "example-listing_id";
    String projectId = "example-project_id";
    String locationId = "example-location_id";
    String dataExchangeId = "example-data_exchange_id";
    String datasetId = "example-dataset_id";
    createListing(listingId, projectId, locationId, dataExchangeId, datasetId);
  }

  public static void createListing(
      String listingId,
      String projectId,
      String locationId,
      String dataExchangeId,
      String datasetId)
      throws IOException {
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      String parent =
          String.format(
              "projects/%s/locations/%s/dataExchanges/%s",
              projectId, locationId, dataExchangeId);

      String dataset = String.format("projects/%s/datasets/%s", projectId, datasetId);
      Listing.BigQueryDatasetSource datasetSource =
          Listing.BigQueryDatasetSource.newBuilder()
              .setDataset(dataset)
              .build();

      Listing listing =
          Listing.newBuilder()
              .setDisplayName("Sample Listing")
              .setBigqueryDataset(datasetSource)
              .build();

      CreateListingRequest request =
          CreateListingRequest.newBuilder()
              .setParent(parent)
              .setListingId(listingId)
              .setListing(listing)
              .build();

      Listing response = client.createListing(request);
      System.out.println("Created listing: " + 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();

/**
 * Creates a listing in a data exchange to share a BigQuery dataset.
 *
 * @param {string} listingId - The ID of the listing to create. Must contain only Unicode letters, numbers (0-9), underscores (_). Max length: 100 bytes.
 * @param {string} projectId - Google Cloud project ID where the data exchange resides.
 * @param {string} locationId - Location of the data exchange and listing (for example, 'us' or 'us-central1').
 * @param {string} dataExchangeId - ID of the parent data exchange where the listing will be created.
 * @param {string} datasetId - ID of the existing BigQuery dataset to be published as a listing.
 */
async function createListing(listingId, projectId, locationId, dataExchangeId, datasetId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}/dataExchanges/${dataExchangeId}`;
    const listing = {
      displayName: 'Example Listing',
      bigqueryDataset: {
        dataset: `projects/${projectId}/datasets/${datasetId}`,
      },
    };

    const request = {
      parent,
      listingId,
      listing,
    };

    const [response] = await client.createListing(request);
    console.log(`Created listing: ${response.name}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Listing ${listingId} already exists.`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Specified parent resource was not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied creating listing: ${err.message}`);
    } else {
      console.error(`Failed to create listing: ${err.message}`);
    }
  }
}

module.exports = { createListing };
```

### 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_listing(
    listing_id: str,
    project_id: str,
    location_id: str,
    data_exchange_id: str,
    dataset_id: str,
) -> None:
    """Creates a listing in an Analytics Hub data exchange.

    Args:
        listing_id: The identifier for the listing. Must contain only letters,
          numbers, and underscores (maximum 100 bytes).
        project_id: The Google Cloud project ID hosting the data exchange and
          BigQuery dataset.
        location_id: The Google Cloud region or multi-region (for example, 'us'
          or 'us-central1').
        data_exchange_id: The identifier of the existing DataExchange.
        dataset_id: The identifier of the BigQuery dataset to share in the
          listing.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    listing = bigquery_analyticshub_v1.Listing(
        display_name="Example Listing",
        description="Dataset shared via Analytics Hub",
        bigquery_dataset=bigquery_analyticshub_v1.Listing.BigQueryDatasetSource(
            dataset=f"projects/{project_id}/datasets/{dataset_id}"
        ),
    )
    parent = f"projects/{project_id}/locations/{location_id}/dataExchanges/{data_exchange_id}"

    request = bigquery_analyticshub_v1.CreateListingRequest(
        parent=parent,
        listing_id=listing_id,
        listing=listing,
    )

    try:
        response = client.create_listing(request=request)
        print(f"Created listing: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to create listing: {e}")
```

## 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).