Writing Cloud Functions

Google Cloud Functions can be written in Node.js, Python, and Go, and are executed in language-specific runtimes. The Cloud Functions execution environment varies by your chosen runtime. The Node.js 6 Runtime, Node.js 8 Runtime, Python Runtime, and Go Runtime pages provide further details about each runtime environment.

Types of Cloud Functions

There are two distinct types of Cloud Functions: HTTP functions and background functions.

HTTP functions

You invoke HTTP functions from standard HTTP requests. These HTTP requests wait for the response and support handling of common HTTP request methods like GET, PUT, POST, DELETE and OPTIONS. When you use Cloud Functions, a TLS certificate is automatically provisioned for you, so all HTTP functions can be invoked via a secure connection.

For details, see Writing HTTP Functions.

Example:

Node.js

const escapeHtml = require('escape-html');

/**
 * HTTP Cloud Function.
 *
 * @param {Object} req Cloud Function request context.
 *                     More info: https://expressjs.com/en/api.html#req
 * @param {Object} res Cloud Function response context.
 *                     More info: https://expressjs.com/en/api.html#res
 */
exports.helloHttp = (req, res) => {
  res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
};

Python (Beta)

from flask import escape

def hello_http(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    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))

Go (Beta)


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

import (
	"encoding/json"
	"fmt"
	"html"
	"net/http"
)

// HelloHTTP is an HTTP Cloud Function with a request parameter.
func HelloHTTP(w http.ResponseWriter, r *http.Request) {
	var d struct {
		Name string `json:"name"`
	}
	if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
		fmt.Fprint(w, "Hello, World!")
		return
	}
	if d.Name == "" {
		fmt.Fprint(w, "Hello, World!")
		return
	}
	fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
}

Background functions

You can use background functions to handle events from your Cloud infrastructure, such as messages on a Cloud Pub/Sub topic, or changes in a Cloud Storage bucket.

For details, see Writing Background Functions.

Example:

Node.js 6

/**
 * Background Cloud Function.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloBackground = (event, callback) => {
  callback(null, `Hello ${event.data.name || 'World'}!`);
};

Node.js 8 (Beta)

/**
 * Background Cloud Function.
 *
 * @param {object} data The event payload.
 * @param {object} context The event metadata.
 */
exports.helloBackground = (data, context) => {
  return `Hello ${data.name || 'World'}!`;
};

Python (Beta)

def hello_background(data, context):
    """Background Cloud Function.
    Args:
         data (dict): The dictionary with data specific to the given event.
         context (google.cloud.functions.Context): The Cloud Functions event
         metadata.
    """
    if data and 'name' in data:
        name = data['name']
    else:
        name = 'World'
    return 'Hello {}!'.format(name)

Go (Beta)


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

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event. Please refer to the docs for
// additional information regarding Pub/Sub events.
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)
	if name == "" {
		name = "World"
	}
	log.Printf("Hello, %s!", name)
	return nil
}

Structuring source code

In order for Cloud Functions to find your function's definition, each runtime has structuring requirements for your source code:

Node.js

For the Node.js runtimes, your function's source code must be exported from a Node.js module, which Cloud Functions loads using a require() call. In order to determine which module to load, Cloud Functions uses the main field in your package.json file. If the main field is not specified, Cloud Functions loads code from index.js.

For example, the following configurations of source code are valid:

  • A single index.js file at the root of your project that exports one or more functions:

    .
    └── index.js
    
  • An index.js file that imports code from a foo.js file and then exports one or more functions:

    .
    ├── index.js
    └── foo.js
    
  • An app.js file that exports one or more functions, with a package.json file that contains "main": "app.js":

    .
    ├── app.js
    └── package.json
    

Python (Beta)

For the Python runtime, your function's entrypoint must be defined in a Python source file at the root of your project named main.py.

For example, the following configurations of source code are valid:

  • A single main.py file at the root of your project that defines one or more functions:

    .
    └── main.py
    
  • A main.py file with a requirements.txt file that specifies dependencies:

    .
    ├── main.py
    └── requirements.txt
    
  • A main.py file that imports code from a local dependency:

    .
    ├── main.py
    └── mylocalpackage/
        ├── __init__.py
        └── myscript.py
    

Go (Beta)

For the Go runtime, your function must be in a Go package at the root of your project. Your function cannot be in package main. Sub-packages are only supported when using Go modules.

For example, the following configurations of source code are valid:

  • A package at the root of your project that exports one or more functions:

    .
    └── function.go
    
  • A package at the root of your project that imports code from a sub-package and exports one or more functions:

    .
    ├── function.go
    ├── go.mod
    └── shared/
        └── shared.go
    
  • A package at the root of your project with a sub-directory that defines a package main:

    .
    ├── cmd/
    |   └── main.go
    └── function.go
    

Specifying dependencies

You specify your function's dependencies idiomatically based on the runtime you are using. For more details, see the appropriate page:

Naming Cloud Functions

Cloud Functions have a "name" property that is set at deploy time, and once set, it cannot be changed. The name of a function is used as its identifier and it must be unique within a region. By default, the name of a function is also used as the entry point into your source code. For example, a function named foo will, by default, execute the foo() function in the source code you deploy. If you want to have a different function executed, you can use the --entry-point flag at deploy time. For details, see the Deploying Cloud Functions documentation.

Next steps

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

Send feedback about...

Cloud Functions Documentation