Using Google BigQuery from Django

In a Django views file we use the Python Client for Google BigQuery to interact with and query the data stored in BigQuery. Note that tables in BigQuery are organized into datasets, so queries must specify both. In this case the dataset id is bigquery-public-data.new_york_taxi_trips, and tlc_yellow_trips_2018 is the table name. For more information on this and other freely available sample data see [Inspecting BigQuery Public Datasets from Google App Engine].

import json
from django.http import HttpResponse
from google.cloud import bigquery

def index(request):
    query = """
      SELECT * FROM
      `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2018`
      LIMIT 1000
    """

    bq_client = bigquery.Client()
    query_job = bq_client.query(query)
    results = query_job.result()
    rows = []
    for row in results:
      for key, val in row.items():
        rows.append(f"{key}: {val}")
    return HttpResponse(json.dumps(rows))

See [Returning BigQuery Results in Apache Arrow Format] for an approach that avoids manual JSON encoding.