Calling Cloud Functions Directly

To support quick iteration and debugging, Cloud Functions provides a call command in the command-line interface and testing functionality in the Cloud Console UI. This allows you to directly invoke a function to ensure it is behaving as expected. This causes the function to execute immediately, even though it may have been deployed to respond to a specific event.

Using the gcloud command-line interface

To directly invoke a function using the gcloud tool, use the gcloud functions call command and supply any data your function expects as JSON in the --data argument. For example:

gcloud functions call YOUR_FUNCTION_NAME --data '{"name":"Keyboard Cat"}'

where YOUR_FUNCTION_NAME is the name of the function you want to execute. The --data argument is sent to your function as follows:

  • For HTTP functions, the data you supply is sent as the body of a POST request.
  • For background functions, the data is passed directly as the event data to your function. For more information on accessing event data in background functions, see Background function parameters.

Using the GCP Console

To directly invoke a function from the Cloud Console, follow these steps:

  1. Go to the Cloud Functions Overview page.

  2. From the list, click the name of the function you want to invoke.

    This takes you to the Function details page.

  3. Click the Testing tab.

  4. In the Triggering event field, enter any data your function expects as JSON.

  5. Click Test the function.

Your function's response appears in the Output field, and logs for the individual execution appear in the Logs field.

Cloud Pub/Sub background function example

This example shows how to directly invoke a background function triggered by Cloud Pub/Sub events:

Node.js

/**
 * 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} message The Pub/Sub message.
 * @param {object} context The event metadata.
 */
exports.helloPubSub = (message, context) => {
  const name = message.data
    ? Buffer.from(message.data, 'base64').toString()
    : 'World';

  console.log(`Hello, ${name}!`);
};

Python

def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         event (dict):  The dictionary with data specific to this type of
         event. The `data` field contains the PubsubMessage message. The
         `attributes` field will contain custom attributes if there are any.
         context (google.cloud.functions.Context): The Cloud Functions event
         metadata. The `event_id` field contains the Pub/Sub message ID. The
         `timestamp` field contains the publish time.
    """
    import base64

    print("""This Function was triggered by messageId {} published at {}
    """.format(context.event_id, context.timestamp))

    if 'data' in event:
        name = base64.b64decode(event['data']).decode('utf-8')
    else:
        name = 'World'
    print('Hello {}!'.format(name))

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event.
type PubSubMessage struct {
	Data []byte `json:"data"`
}

// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(ctx context.Context, m PubSubMessage) error {
	name := string(m.Data) // Automatically decoded from base64.
	if name == "" {
		name = "World"
	}
	log.Printf("Hello, %s!", name)
	return nil
}

Java


import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import functions.eventpojos.PubSubMessage;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HelloPubSub implements BackgroundFunction<PubSubMessage> {
  private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());

  @Override
  public void accept(PubSubMessage message, Context context) {
    String name = "world";
    if (message != null && message.getData() != null) {
      name = new String(
          Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
          StandardCharsets.UTF_8);
    }
    logger.info(String.format("Hello %s!", name));
    return;
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.PubSub.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloPubSub
{
    public class Function : ICloudEventFunction<MessagePublishedData>
    {
        private readonly ILogger _logger;

        public Function(ILogger<Function> logger) =>
            _logger = logger;

        public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
        {
            string nameFromMessage = data.Message?.TextData;
            string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
            _logger.LogInformation("Hello {name}", name);
            return Task.CompletedTask;
        }
    }
}

To directly invoke the function, you need to send a PubsubMessage, which expects base64-encoded data, as the event data:

Node.js

DATA=$(printf 'Hello!'|base64) && gcloud functions call helloPubSub --data '{"data":"'$DATA'"}'

Python

DATA=$(printf 'Hello!'|base64) && gcloud functions call hello_pubsub --data '{"data":"'$DATA'"}'

Go

DATA=$(printf 'Hello!'|base64) && gcloud functions call HelloPubSub --data '{"data":"'$DATA'"}'

Java

DATA=$(printf 'Hello!'|base64) && gcloud functions call java-hello-pubsub --data '{"data":"'$DATA'"}'

C#

DATA=$(printf 'Hello!'|base64) && gcloud functions call csharp-hello-pubsub --data '{"data":"'$DATA'"}'

You can also invoke the function from the Cloud Console UI: simply use the same event data in the Triggering event field.