Writing Cloud Functions

Google Cloud Functions can be written in Node.js and Python, 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, and Python Runtime pages provide further details about each runtime environment, including language versions, file naming requirements, and how to handle dependencies.

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))

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)

Structuring source code

In order for Cloud Functions to find your function's definition, each runtime has certain structuring requirements for your source code. For more details, see the appropriate runtime page:

Specifying dependencies

You specify your function's dependencies idiomatically based on the runtime you are using. For more details, see the appropriate runtime 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