Learn How to Run Serverless Code with GCP Cloud Functions

Published:16 December 2022 - 5 min. read

Nicholas Xuan Nguyen Image

Nicholas Xuan Nguyen

Read more tutorials by Nicholas Xuan Nguyen!

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Serverless computing is becoming increasingly popular in reducing computing costs and improving scalability. And if you are looking for a serverless environment, Google Cloud Platform (GCP) offers its own in the form of GCP Cloud Functions.

Why stress yourself out worrying about infrastructure when you can focus on building applications instead? Let GCP Cloud Functions handle the rest! In this tutorial, you will learn how to create your first serverless function with GCP Cloud Functions.

Read on and get those codes running without relying on a server!

Prerequisites

This tutorial will be a hands-on demonstration. To follow along, ensure you have a GCP account and access to the GCP Console. The free trial account should be sufficient for this tutorial.

Creating a Google Cloud Project

Before setting up a serverless environment in GCP, your first step is to create a Google Cloud project. A project is an organizational unit in GCP that contains related services and resources. Every GCP service will be associated with one or more projects.

💡 Creating a new project for each application you develop is strongly recommended. Using existing projects can make managing resources confusing.

To create a Google Cloud project, follow these steps:

1. Open your favorite web browser, and navigate to the cloud resource manager in the GCP Console.

2. Next, click CREATE PROJECT, as shown below, to create a new project.

 Creating a new Google Cloud project
Creating a new Google Cloud project

3. On the next screen, configure the new project with the following:

  • Project name – Provide a unique name for the project (i.e., GCP-cloud-functions-project).Project ID – GCP will generate a unique ID for your project automatically, and it cannot be changed later. This tutorial goes with the pre-generated ID, but if you prefer a different one, click on EDIT and provide a custom project ID.Location – Select your preferred parent organization or folder for your project if you have one.
Once filled up, click the CREATE button to create your project.

Creating a new Google Cloud project
Creating a new Google Cloud project

Once completed, you will receive a notification indicating that you have successfully created the project.

Confirming the project creation is successful
Confirming the project creation is successful

You will also see the newly-created project listed in the projects list, as shown below.

Viewing the newly-created project
Viewing the newly-created project

4. Now, navigate to the project selector and select your newly created project as the current project.

Selecting the current project
Selecting the current project

Enabling the GCP Cloud Functions APIs

Before creating a cloud function, you will have to enable the required APIs. Enabling the APIs will grant permission to access and use the services.

Navigate to Enable API page for Google Cloud Functions, and click Next to confirm making the changes to your project.

Confirming making changes to the project/
Confirming making changes to the project/

On the next screen, click ENABLE to enable all required APIs, like Cloud Functions API, Cloud Pub/Sub, and others.

Enabling the required APIs
Enabling the required APIs

Once the required APIs are enabled, you will see a notification like the one below.

Confirming APIs are successfully enabled
Confirming APIs are successfully enabled

Creating and Deploying a GCP Cloud Functions

1. Navigate to the Functions Overview page in the GCP Console, and click CREATE FUNCTION to create a new function.

Creating a new function
Creating a new function

2. On the next screen, configure the new function as follows:

EnvironmentSelect 2nd gen from the dropdown field. GCP offers two versions of Cloud Functions (1st and 2nd Generation). In this tutorial, you will use the 2nd generation since it provides more enhanced features. One of its most notable features is it supports a stable and secure HTTPS endpoint URL.
Function nameProvide a unique name for the function (gcp-cloud-functions-1). The name can only contain lowercase letters, numbers, and hyphens.
RegionSelect a region closest to you from the dropdown field.
AuthenticationSelect the Allow unauthenticated invocations option for testing purposes. This option allows you to trigger the function without complicated authentication.

Keep the other settings as is, and click Next.

Configuring the cloud function
Configuring the cloud function

3. Configure the code for the function with the following:

  • Runtime – Select Nodejs 16 version from the dropdown field. This runtime version is stable and secure and supports all the latest features of the Node.js language.Source Code – Select Inline Editor to write the function code.Replace the existing code in the editor with the one below, a basic function to send a “Hello World” output.

# Imports the functions framework library.
const functions = require('@google-cloud/functions-framework');

# Creates a web endpoint that sends a “Hello World” response when triggered.
functions.http('helloHttp', (req, res) => {
 res.send(`Hello ${req.query.name || req.body.name || 'World'}!`);
});
Configuring code and runtime
Configuring code and runtime

4. Next, scroll down to the bottom, and click Deploy to deploy your Cloud Function, which takes a few seconds to complete.

As you can see, GCP Cloud Functions allows developers like yourself to write code that runs without managing any servers.

Deploying the GCP Cloud Function
Deploying the GCP Cloud Function

5. Now, click REFRESH to reload the list of deployed functions.

Once the deployment completes, you will see a green checkmark next to the Environment column, as shown below. This checkmark indicates your GCP Cloud Functions is active and ready for use.

Verifying the GCP Cloud Function is active and ready for use
Verifying the GCP Cloud Function is active and ready for use

Testing the GCP Cloud Function

At this point, you have successfully created and deployed the GCP Cloud Function. But how do you know it is working as expected? You will test your deployed function by navigating to the function’s endpoint URL in your browser.

To test your GCP Cloud Function deployment:

1. Click the name (hyperlink) of your Cloud Function to open its Overview page.

Accessing the GCP Cloud Function’s overview page
Accessing the GCP Cloud Function’s overview page

2. Next, click the copy icon to copy the endpoint URL, as shown below.

Copying the endpoint URL
Copying the endpoint URL

Navigate to the URL you copied in step three to a new tab in your browser.

If all goes well, you will get the Hello World message, as shown below, which indicates your deployed function works.

Testing the Cloud Function deployment
Testing the Cloud Function deployment

4. Now, scroll down and view the graphs and charts of the function. These graphs will help you to identify any errors or optimize the performance of the functions. The following screenshots show:

  • The Invocations/Second graph – This graph shows the number of times your function is called every second.
Viewing the Invocations/Second graph
Viewing the Invocations/Second graph

The Memory utilization (MB/call) graph – This graph shows the average memory used by your function with each invocation. Many more helpful graphs are available, such as Memory usage, Duration time, and Error rate. Feel free to explore them.

Viewing the Memory utilization(MB/call) graph
Viewing the Memory utilization(MB/call) graph

Cleaning Up Resources

Now you have tested your deployment works, ensure you avoid incurring charges by cleaning up your resources.

1. Navigate to the cloud resource manager page in the GCP Console.

2. Tick the checkbox next to your project name, and click DELETE to delete the selected project. This action deletes all associated resources of your project, such as cloud functions, APIs, and so on.

Deleting a GCP project
Deleting a GCP project

3. Finally, enter the project ID when prompted, and click SHUT DOWN to confirm the deletion.

You have a grace period of 30 days to undo the deletion. But beyond that period, your project and all its resources get permanently deleted.

Confirming GCP project deletion
Confirming GCP project deletion

Conclusion

Serverless computing provides a cost-effective way to develop and scale applications. GCP Cloud Function and AWS Lambda are the two major competitors in cloud technology. And in this tutorial, you have learned how to create and deploy a basic GCP Cloud Function via GCP.

You can use these technologies to quickly deploy code and build powerful applications without server management involved.

With this newfound knowledge, why not use Terraform to automate creating and deploying cloud functions?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!