Google Cloud BigQuery Client (Async)

7.1.0 · active · verified Thu Apr 16

gcloud-rest-bigquery is an asynchronous Python client for Google Cloud BigQuery, built on top of the gcloud-aio client library. It provides an asyncio-native interface for interacting with BigQuery APIs, leveraging aiohttp for HTTP requests. The library is part of the gcloud-aio monorepo, which sees frequent updates across its various Google Cloud service clients. The current version is 7.1.0.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the BigqueryClient using default Google Cloud credentials (e.g., `gcloud auth application-default login` or `GOOGLE_APPLICATION_CREDENTIALS`), run a simple SQL query, and fetch its results asynchronously. Ensure the `GCLOUD_PROJECT` environment variable is set to your Google Cloud project ID.

import asyncio
import os
from gcloud_aio_auth import build_default_credentials
from gcloud_aio_bigquery import BigqueryClient

async def main():
    project_id = os.environ.get("GCLOUD_PROJECT", "")
    if not project_id:
        print("Please set the GCLOUD_PROJECT environment variable.")
        return

    # Using default credentials (e.g., from gcloud CLI, service account JSON in GOOGLE_APPLICATION_CREDENTIALS)
    async with build_default_credentials(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    ) as credentials:
        async with BigqueryClient(
            project=project_id, credentials=credentials
        ) as client:
            # Execute a simple query
            print(f"Running query in project: {project_id}")
            query_job = await client.query(
                project_id=project_id,
                query="SELECT 1 AS one, 'hello' AS greeting",
                use_legacy_sql=False,
                location="US" # Or your preferred dataset location
            )

            # Wait for the job to complete and fetch results
            results = await client.get_job_results(
                project_id=project_id,
                job_id=query_job["jobReference"]["jobId"],
                location=query_job["jobReference"]["location"]
            )

            print("Query results:")
            if results and "rows" in results:
                for row in results["rows"]:
                    # Each 'f' element corresponds to a column, 'v' is the value
                    print([col["v"] for col in row["f"]])
            else:
                print("No rows returned or unexpected result format.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →