6

How can I query a BigQuery dataset and get a list of all the tables in the dataset? As far as I know, I can only use the BigQuery API, but I cannot authenticate, despite passing an API key.

    url = f"https://bigquery.googleapis.com/bigquery/v2/projects/{params['project_id']}/datasets/{params['dataset_id']}/tables?key={params['api_key']}"
    response = requests.get(url)
    data = response.json()
    pprint.pprint(data)

2

2 Answers 2

22

As Mikhail said, its explained in the docs. Here is the answer:

from google.cloud import bigquery

# TODO(developer): Construct a BigQuery client object.
# client = bigquery.Client()

# TODO(developer): Set dataset_id to the ID of the dataset that contains
#                  the tables you are listing.
# dataset_id = 'your-project.your_dataset'

tables = client.list_tables(dataset_id)

print("Tables contained in '{}':".format(dataset_id))
for table in tables:
    print("{}.{}.{}".format(table.project, table.dataset_id, table.table_id))
Sign up to request clarification or add additional context in comments.

Comments

0

I could expand on John's answer and add:

from google.cloud import bigquery
client = bigquery.Client()
datasets = list(client.list_datasets())  # Make an API request.
project = client.project

if datasets:
    print("Datasets in project {}:".format(project))
    for dataset in datasets:
        print("\t{}".format(dataset.dataset_id))
        tables = client.list_tables(dataset.dataset_id)

        print("Tables contained in '{}':".format(dataset.dataset_id))
        for table in tables:
            print("{}.{}.{}".format(table.project, table.dataset_id, table.table_id))

else:
    print("{} project does not contain any datasets.".format(project))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.