Google Cloud BigQuery Client (async)

7.1.0 · active · verified Wed Apr 01

gcloud-aio-bigquery is an asynchronous Python client for Google Cloud BigQuery, built on `asyncio` and `aiohttp`. It's part of the `gcloud-aio-*` family, providing an asynchronous HTTP implementation of Google Cloud client libraries. The current version is 7.1.0 and it maintains an active release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `BigQuery` client, authenticate using `gcloud-aio-auth`, and execute a simple SQL query against a public BigQuery dataset. Ensure your `GOOGLE_CLOUD_PROJECT` environment variable is set to your Google Cloud project ID, and `GOOGLE_APPLICATION_CREDENTIALS` points to your service account key file for local execution.

import asyncio
import os
import aiohttp
from gcloud.aio.auth import Token
from gcloud.aio.bigquery import BigQuery

async def main():
    # Ensure GOOGLE_CLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS
    # are set in your environment for authentication.
    project = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-gcp-project-id') # Replace with your project ID
    
    async with aiohttp.ClientSession() as session:
        # Obtain Google Cloud credentials token
        token = await Token(session=session).get()
        
        # Initialize BigQuery client
        client = BigQuery(project=project, session=session, token=token)

        query = """
            SELECT name, SUM(number) as total_babies
            FROM `bigquery-public-data.usa_names.usa_1910_2013`
            WHERE state = 'TX'
            GROUP BY name
            ORDER BY total_babies DESC
            LIMIT 5
        """
        
        print(f"Executing query for project: {project}")
        job_id, result = await client.query_and_wait(query)
        
        print(f"Query Job ID: {job_id}")
        print("Top 5 baby names in Texas (1910-2013):")
        
        for row in result['rows']:
            print(f"- {row['name']}: {row['total_babies']}")

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

view raw JSON →