Cloud Pub/Sub Tutorial

This simple tutorial demonstrates writing, deploying, and triggering a Background Cloud Function with a Cloud Pub/Sub trigger. To learn more about Cloud Pub/Sub, see the Cloud Pub/Sub documentation.

Objectives

Costs

This tutorial uses billable components of Cloud Platform, including:

  • Google Cloud Functions
  • Google Cloud Pub/Sub

Use the Pricing Calculator to generate a cost estimate based on your projected usage.

New Cloud Platform users might be eligible for a free trial.

Before you begin

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Select or create a GCP project.

    Go to the Manage resources page

  3. Make sure that billing is enabled for your project.

    Learn how to enable billing

  4. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Enable the APIs

  5. Install and initialize the Cloud SDK.
  6. Update and install gcloud components:

    Node.js 6

    gcloud components update

    Node.js 8 (Beta)

    gcloud components update &&
    gcloud components install beta

    Python (Beta)

    gcloud components update &&
    gcloud components install beta
  7. Prepare your development environment.

Preparing the application

  1. Clone the sample app repository to your local machine:

    Node.js 6

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    Node.js 8 (Beta)

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

    Python (Beta)

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    Alternatively, you can download the sample as a zip file and extract it.

  2. Change to the directory that contains the Cloud Functions sample code for accessing Cloud Pub/Sub:

    Node.js 6

    cd nodejs-docs-samples/functions/helloworld/

    Node.js 8 (Beta)

    cd nodejs-docs-samples/functions/node8/

    Python (Beta)

    cd python-docs-samples/functions/helloworld/

  3. Take a look at the sample code:

    Node.js 6

    /**
     * Background Cloud Function to be triggered by Pub/Sub.
     * This function is exported by index.js, and executed when
     * the trigger topic receives a message.
     *
     * @param {object} event The Cloud Functions event.
     * @param {function} callback The callback function.
     */
    exports.helloPubSub = (event, callback) => {
      const pubsubMessage = event.data;
      const name = pubsubMessage.data ? Buffer.from(pubsubMessage.data, 'base64').toString() : 'World';
    
      console.log(`Hello, ${name}!`);
    
      callback();
    };

    Node.js 8 (Beta)

    /**
     * Background Cloud Function to be triggered by Pub/Sub.
     * This function is exported by index.js, and executed when
     * the trigger topic receives a message.
     *
     * @param {object} data The event payload.
     * @param {object} context The event metadata.
     */
    exports.helloPubSub = (data, context) => {
      const pubSubMessage = data;
      const name = pubSubMessage.data ? Buffer.from(pubSubMessage.data, 'base64').toString() : 'World';
    
      console.log(`Hello, ${name}!`);
    };

    Python (Beta)

    def hello_pubsub(data, context):
        """Background Cloud Function to be triggered by Pub/Sub.
        Args:
             data (dict): The dictionary with data specific to this type of event.
             context (google.cloud.functions.Context): The Cloud Functions event
             metadata.
        """
        import base64
    
        if 'data' in data:
            name = base64.b64decode(data['data']).decode('utf-8')
        else:
            name = 'World'
        print('Hello, {}!'.format(name))

Deploying the function

To deploy the function with a Cloud Pub/Sub trigger, run the following command in the directory where the sample code is located:

Node.js 6

gcloud functions deploy helloPubSub --runtime nodejs6 --trigger-resource YOUR_TOPIC_NAME --trigger-event google.pubsub.topic.publish

Node.js 8 (Beta)

gcloud functions deploy helloPubSub --runtime nodejs8 --trigger-resource YOUR_TOPIC_NAME --trigger-event google.pubsub.topic.publish

Python (Beta)

gcloud functions deploy hello_pubsub --runtime python37 --trigger-resource YOUR_TOPIC_NAME --trigger-event google.pubsub.topic.publish

where YOUR_TOPIC_NAME is the name of the Cloud Pub/Sub topic to which the function will be subscribed.

Triggering the function

  1. Publish a message to your Cloud Pub/Sub topic. In this example, the message is a name that the function will include in a greeting:

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    Replace YOUR_TOPIC_NAME with the name of your Cloud Pub/Sub topic, and YOUR_NAME with an arbitrary string.

  2. Check the logs to be sure the executions have completed:

    gcloud functions logs read --limit 50
    

Cleaning up

To avoid incurring charges to your Google Cloud Platform account for the resources used in this tutorial:

Deleting the project

The easiest way to eliminate billing is to delete the project you created for the tutorial.

To delete the project:

  1. In the GCP Console, go to the Projects page.

    Go to the Projects page

  2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Deleting the Cloud Function

Deleting Cloud Functions does not remove any resources stored in Cloud Storage.

To delete the Cloud Function you created in this tutorial, run the following command:

Node.js

gcloud functions delete helloPubSub 

Python (Beta)

gcloud functions delete hello_pubsub 

You can also delete Cloud Functions from the Google Cloud Platform Console.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Functions Documentation