This guide explains how to authenticate using user accounts for access to the Google BigQuery API when your application is installed onto users' machines.
A user credential can be used to ensure the application accesses only BigQuery tables that are available to the end user. A user credential can run queries against only the end user's Cloud Platform project rather than the application's project, meaning the user is billed for queries instead of the application.
Before you begin
- Create a new Google Cloud Platform project representing your installed application.
- Install the BigQuery client libraries.
Install additional libraries.
PythonInstall the oauthlib integration for Google Auth.
pip install --upgrade google-auth-oauthlib
Setting up your client credentials
- Go to the API credentials page in the Cloud Platform Console.
- Fill out the required fields on the OAuth consent screen.
On the credentials
page, click the Create credentials button.
Choose OAuth client ID.
- Select Other as the application type, and then click Create.
Download the credentials by clicking the Download JSON button.
Save the credentials file to
client_secrets.json. This file must be distributed with your application.
Authenticating and calling the API
Use the client credentials to perform the
def authenticate_and_query(project, query, launch_browser=True): from google_auth_oauthlib import flow appflow = flow.InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', scopes=['https://www.googleapis.com/auth/bigquery']) if launch_browser: appflow.run_local_server() else: appflow.run_console() run_query(appflow.credentials, project, query)
Use the authenticated credentials to connect to the BigQuery API.
def run_query(credentials, project, query): from google.cloud import bigquery client = bigquery.Client(project=project, credentials=credentials) query_job = client.query(query) # Print the results. for row in query_job.result(): # Wait for the job to complete. print(row)
When you run the sample code, it will launch a browser requesting access to the project associated with the client secrets. The resulting credentials can then be used to access the user's BigQuery resources, because the sample requested the BigQuery scope.