Create a Cloud Run function that uses BigQuery to submit a query and return results. Stay organized with collections Save and categorize content based on your preferences.
This tutorial shows you how to write an HTTP Cloud Run functionthat submits a query to BigQuery.
Objectives
In this tutorial, you will:
Costs
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage, use thepricing calculator.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Run Admin API, and Cloud Build APIs.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.- Set up your Cloud Run development environmentin your Google Cloud project.
If you are under a domain restriction organization policyrestricting unauthenticated invocations for your project, you will need to access your deployed service as described underTesting private services.
Required roles
To get the permissions that you need to deploy Cloud Run services from source, ask your administrator to grant you the following IAM roles:
- Cloud Run Source Developer (
roles/run.sourceDeveloper) on your project - Service Usage Consumer (
roles/serviceusage.serviceUsageConsumer) on the Cloud Run service - Service Account User (
roles/iam.serviceAccountUser) on the service identity - BigQuery Job User (
roles/bigquery.jobUser) on the service identity
For a list of IAM roles and permissions that are associated withCloud Run, seeCloud Run IAM rolesandCloud Run IAM permissions.If your Cloud Run service interfaces withGoogle Cloud APIs, such as Cloud Client Libraries, see theservice identity configuration guide.For more information about granting roles, seedeployment permissionsandmanage access.
Roles for the Cloud Build service account
You or your administrator must grant the Cloud Build service account thefollowing IAM role.
Click to view required roles for the Cloud Build service account
Cloud Build automatically uses theCompute Engine default service account as the default Cloud Build service account to build your source code and Cloud Run resource, unless you override this behavior. For Cloud Build to build your sources, ask your administrator to grantCloud Run Builder (roles/run.builder) to the Compute Engine default service account on your project:
gcloudprojectsadd-iam-policy-bindingPROJECT_ID\--member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com\--role=roles/run.builder
ReplacePROJECT_NUMBER with your Google Cloud project number, andPROJECT_ID with your Google Cloud project ID. For detailed instructions on how to find your project ID, and project number, seeCreating and managing projects.
Granting the Cloud Run builder role to the Compute Engine default service account takes a couple of minutes topropagate.
Note: Theiam.automaticIamGrantsForDefaultServiceAccounts organization policy constraint prevents the Editor role from being automatically granted to default service accounts. If you created your organization after May 3, 2024, this constraint is enforced by default.
We strongly recommend that you enforce this constraint to disable the automatic role grant. If you disable the automatic role grant, you must decide which roles to grant to the default service accounts, and thengrant these roles yourself.
If the default service account already has the Editor role, we recommend that you replace the Editor role with less permissive roles.To safely modify the service account's roles, usePolicy Simulator to see the impact of the change, and thengrant and revoke the appropriate roles.
Prepare the application
Clone the sample application repository to your local machine:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.gitAlternatively,download the sample as a zip fileand extract it.
Change to the directory that contains the sample code:
cd nodejs-docs-samples/functions/v2/helloBigQueryTake a look at the sample code. The sample submits a query for words thatoccur at least 400 times in the specified dataset, and returns the result.
// Import the Google Cloud client libraryconst{BigQuery}=require('@google-cloud/bigquery');constbigquery=newBigQuery();constfunctions=require('@google-cloud/functions-framework');/** * HTTP Cloud Function that returns BigQuery query results * * @param {Object} req Cloud Function request context. * @param {Object} res Cloud Function response context. */functions.http('helloBigQuery',async(req,res)=>{// Define the SQL query// Queries the public Shakespeare dataset using named query parameterconstsqlQuery=` SELECT word, word_count FROM \`bigquery-public-data.samples.shakespeare\` WHERE corpus = @corpus AND word_count >= @min_word_count ORDER BY word_count DESC`;constoptions={query:sqlQuery,// Location must match that of the dataset(s) referenced in the query.location:'US',params:{corpus:'romeoandjuliet',min_word_count:400},};// Execute the querytry{const[rows]=awaitbigquery.query(options);// Send the resultsres.status(200).send(rows);}catch(err){console.error(err);res.status(500).send(`Error querying BigQuery:${err}`);}});
Deploy the function
To deploy the function with an HTTP trigger:
Run the following command in the directory that contains the sample code:
gcloudrundeployFUNCTION\--source.\--functionFUNCTION_ENTRYPOINT\--base-imageBASE_IMAGE\--regionREGION\--allow-unauthenticated
Replace:
FUNCTION with the name of the function you aredeploying, for example
my-bigquery-function. You can omit this parameterentirely, but you will be prompted for the name if you omit it.FUNCTION_ENTRYPOINT with the entry point to your function inyour source code. This is the code Cloud Run executes when yourfunction runs. The value of this flag must be a function name orfully-qualified class name that exists in your source code. The entry pointyou must specify for the sample function is
helloBigQuery.BASE_IMAGE with the base image environment for yourfunction, for example,
nodejs24. For details about baseimages and the packages included in each image, seeRuntimes base images.REGION with the Google Cloudregion where you want to deployyour function. For example,
europe-west1.
Optional:
- If you are creating a public HTTP function, for example a webhook,specify the
--allow-unauthenticatedflag. This flag assigns theCloud Run IAM Invoker role to the special identifierallUser. You canuse IAM to edit this settinglater after you create the service.
Test the function
When the function finishes deploying, copy the
uriproperty.Visit this URI in your browser.
You should see a list of the words thatmatch the query criteria, and how many times each word appears in thetarget dataset.
Clean up
To avoid additional charges to your Google Cloud account, delete all the resourcesyou deployed with this tutorial.
Delete the project
If you created a new project for this tutorial, delete the project.If you used an existing project and need to keep it without the changes you addedin this tutorial,delete resources that you created for the tutorial.
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
Delete tutorial resources
Delete the Cloud Run service you deployed in this tutorial.Cloud Run services don't incur costs until they receive requests.
To delete your Cloud Run service, run the following command:
gcloudrunservicesdeleteSERVICE-NAME
ReplaceSERVICE-NAME with the name of your service.
You can also delete Cloud Run services from theGoogle Cloud console.
Remove the
gclouddefault region configuration you added during tutorialsetup:gcloudconfigunsetrun/regionRemove the project configuration:
gcloud config unset project
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.