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): 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): client = bigquery.Client(project=project, credentials=credentials) query_job = client.run_async_query(str(uuid.uuid4()), query) query_job.use_legacy_sql = False query_job.begin() wait_for_job(query_job) query_results = query_job.results() rows = query_results.fetch_data(max_results=10) for row in rows: 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.