Google Cloud Functions are a fully managed and serverless way to run event-driven code. They react to demand from zero to planet-scale and come with integrated monitoring, logging, and debugging. All you need to do is plug in your code! In this lab, we will introduce ourselves to Cloud Functions by writing our first function that will simply respond to an HTTP trigger; in other words, our function will run when you send a request to its URL.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Enable APIs and Set Up the Cloud Shell
To help us create our first Cloud Function, we will enable some APIs and get ready to use the Cloud Shell editor and terminal.
- Inside the GCP console, click the Activate Cloud Shell icon.
- Click the down triangle next to the project ID at the top of the page.
- When the dialog opens, copy the current Project ID.
- In the Cloud Shell, enter the following command:
gcloud config set project <PROJECT_ID>
- Then, run this command to enable the necessary APIs:
gcloud services enable cloudbuild.googleapis.com cloudfunctions.googleapis.com
- Create a directory for your function and move into that directory.
- In the Cloud Shell, click Open Editor. Then choose Open in a new window.
- When the editor has opened in a new tab, go back to your original tab and click Open Terminal to get the terminal back.
You are now ready to start building your first Cloud Function.
- Write the Hello World Function
In the
helloworld
directory, create themain.py
file using the Cloud Shell editor:from flask import escape def hello_http(request): request_json = request.get_json(silent=True) request_args = request.args if request_json and 'name' in request_json: name = request_json['name'] elif request_args and 'name' in request_args: name = request_args['name'] else: name = 'World' return 'Hello {}!'.format(escape(name))
Also inside the
helloworld
directory, create therequirements.txt
file, specifying the Flask library and the version of the library. UseFlask==2.0.3
- Deploy and Test the Hello World Function
- Back in the Cloud Shell terminal, and inside the
helloworld
directory, deploy the Hello World function. - From the GCP menu, select Cloud Functions from the Compute section. Then select the hello_http function. Observe the various tabs that show you the details of your deployed function.
- Under the Trigger tab, click the URL and follow the redirect to trigger your function and see the "Hello World!" response.
- To customize the response, add a query parameter to the end of the URL (for example,
?name=Cloud%20Gurus
).
- Back in the Cloud Shell terminal, and inside the