HTTP Triggers

You can invoke Cloud Functions with an HTTP request using the POST, PUT, GET, DELETE, and OPTIONS HTTP methods. To create an HTTP endpoint for your function, specify --trigger-http as the trigger type when deploying your function. From the caller's perspective, HTTP invocations are synchronous, meaning that the result of the function execution will be returned in the response to the HTTP request.

For example, the following gcloud command deploys a function to the Node.js runtime that will be triggered by HTTP requests:

gcloud functions deploy FUNCTION_NAME --runtime nodejs16 --trigger-http --allow-unauthenticated

HTTP functions require authentication by default. The --allow-unauthenticated flag lets you reach the function without authentication. To require authentication, omit the flag.

You can use the commonly available cURL command-line utility to invoke HTTP functions. The following cURL command makes a POST request with some data to the URL of a deployed HTTP function:

curl -X POST "" -H "Content-Type:application/json" --data '{"name":"Keyboard Cat"}'


  • YOUR_REGION is the region where your function is deployed,
  • YOUR_PROJECT_ID is your Google Cloud Platform project ID, and
  • FUNCTION_NAME is the name of the HTTP function you deployed.

The trigger URL for an HTTP function can be seen after the function is deployed, or queried at any time using the gcloud functions describe command.

You can also trigger your HTTP functions directly through the gcloud CLI. The following command calls a function and sends it some data in the body of an HTTP POST request:

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

Code sample


const functions = require('@google-cloud/functions-framework');
const escapeHtml = require('escape-html');

 * Responds to an HTTP request using data from the request body parsed according
 * to the "content-type" header.
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
functions.http('helloHttp', (req, res) => {
  res.send(`Hello ${escapeHtml( || || 'World')}!`);


from flask import escape
import functions_framework

def hello_http(request):
    """HTTP Cloud Function.
        request (flask.Request): The request object.
        The response text, or any set of values that can be turned into a
        Response object using `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']
        name = 'World'
    return 'Hello {}!'.format(escape(name))


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

import (

// 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!")
	if d.Name == "" {
		fmt.Fprint(w, "Hello, World!")
	fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))


import java.util.logging.Logger;

public class HelloHttp implements HttpFunction {
  private static final Logger logger = Logger.getLogger(HelloHttp.class.getName());

  private static final Gson gson = new Gson();

  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    // Check URL parameters for "name" field
    // "world" is the default value
    String name = request.getFirstQueryParameter("name").orElse("world");

    // Parse JSON request and check for "name" field
    try {
      JsonElement requestParsed = gson.fromJson(request.getReader(), JsonElement.class);
      JsonObject requestJson = null;

      if (requestParsed != null && requestParsed.isJsonObject()) {
        requestJson = requestParsed.getAsJsonObject();

      if (requestJson != null && requestJson.has("name")) {
        name = requestJson.get("name").getAsString();
    } catch (JsonParseException e) {
      logger.severe("Error parsing JSON: " + e.getMessage());

    var writer = new PrintWriter(response.getWriter());
    writer.printf("Hello %s!", name);


using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace HelloHttp
    public class Function : IHttpFunction
        private readonly ILogger _logger;

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

        public async Task HandleAsync(HttpContext context)
            HttpRequest request = context.Request;
            // Check URL parameters for "name" field
            // "world" is the default value
            string name = ((string) request.Query["name"]) ?? "world";

            // If there's a body, parse it as JSON and check for "name" field.
            using TextReader reader = new StreamReader(request.Body);
            string text = await reader.ReadToEndAsync();
            if (text.Length > 0)
                    JsonElement json = JsonSerializer.Deserialize<JsonElement>(text);
                    if (json.TryGetProperty("name", out JsonElement nameElement) &&
                        nameElement.ValueKind == JsonValueKind.String)
                        name = nameElement.GetString();
                catch (JsonException parseException)
                    _logger.LogError(parseException, "Error parsing JSON request");

            await context.Response.WriteAsync($"Hello {name}!");


require "functions_framework"
require "cgi"
require "json"

FunctionsFramework.http "hello_http" do |request|
  # The request parameter is a Rack::Request object.
  # See
  name = request.params["name"] ||
         (JSON.parse(["name"] rescue nil) ||
  # Return the response body as a string.
  # You can also return a Rack::Response object, a Rack response array, or
  # a hash which will be JSON-encoded into a response.
  "Hello #{CGI.escape_html name}!"



use Google\CloudFunctions\FunctionsFramework;
use Psr\Http\Message\ServerRequestInterface;

// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=http` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::http('helloHttp', 'helloHttp');

function helloHttp(ServerRequestInterface $request): string
    $name = 'World';
    $body = $request->getBody()->getContents();
    if (!empty($body)) {
        $json = json_decode($body, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            throw new RuntimeException(sprintf(
                'Could not parse body: %s',
        $name = $json['name'] ?? $name;
    $queryString = $request->getQueryParams();
    $name = $queryString['name'] ?? $name;

    return sprintf('Hello, %s!', htmlspecialchars($name));

HTTP Request/Response Structure

HTTP-triggered functions receive events via language-idiomatic HTTP frameworks. See the code samples above for more information.

Next steps

See the HTTP Tutorial for an example of how to implement an HTTP function, or HTTP Functions to learn more about writing HTTP functions.