HTTP method types

Shows how to handle HTTP method types (such as GET, PUT, and POST) in Cloud Functions.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

C#

using Google.Cloud.Functions.Framework;
using Microsoft.AspNetCore.Http;
using System.Net;
using System.Threading.Tasks;

namespace HttpRequestMethod
{
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            HttpResponse response = context.Response;
            switch (context.Request.Method)
            {
                case "GET":
                    response.StatusCode = (int) HttpStatusCode.OK;
                    await response.WriteAsync("Hello world!");
                    break;
                case "PUT":
                    response.StatusCode = (int) HttpStatusCode.Forbidden;
                    await response.WriteAsync("Forbidden!");
                    break;
                default:
                    response.StatusCode = (int) HttpStatusCode.MethodNotAllowed;
                    await response.WriteAsync("Something blew up!");
                    break;
            }
        }
    }
}

C++

#include <google/cloud/functions/http_request.h>
#include <google/cloud/functions/http_response.h>

namespace gcf = ::google::cloud::functions;

gcf::HttpResponse http_method(gcf::HttpRequest request) {  // NOLINT
  if (request.verb() == "GET") {
    return gcf::HttpResponse{}
        .set_header("content-type", "text/plain")
        .set_payload("Hello World!");
  }

  return gcf::HttpResponse{}.set_result(
      request.verb() == "POST" ? gcf::HttpResponse::kForbidden
                               : gcf::HttpResponse::kMethodNotAllowed);
}

Go


// Package http provides a set of HTTP Cloud Functions samples.
package http

import (
	"fmt"
	"net/http"
)

// HelloHTTPMethod is an HTTP Cloud function.
// It uses the request method to differentiate the response.
func HelloHTTPMethod(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		fmt.Fprint(w, "Hello World!")
	case http.MethodPut:
		http.Error(w, "403 - Forbidden", http.StatusForbidden)
	default:
		http.Error(w, "405 - Method Not Allowed", http.StatusMethodNotAllowed)
	}
}

Java


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.HttpURLConnection;

public class HttpMethod implements HttpFunction {
  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {

    BufferedWriter writer = response.getWriter();

    switch (request.getMethod()) {
      case "GET":
        response.setStatusCode(HttpURLConnection.HTTP_OK);
        writer.write("Hello world!");
        break;
      case "PUT":
        response.setStatusCode(HttpURLConnection.HTTP_FORBIDDEN);
        writer.write("Forbidden!");
        break;
      default:
        response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD);
        writer.write("Something blew up!");
        break;
    }
  }
}

Node.js

/**
 * Responds to a GET request with "Hello World!". Forbids a PUT request.
 *
 * @example
 * gcloud functions call helloHttp
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
exports.helloHttp = (req, res) => {
  switch (req.method) {
    case 'GET':
      res.status(200).send('Hello World!');
      break;
    case 'PUT':
      res.status(403).send('Forbidden!');
      break;
    default:
      res.status(405).send({error: 'Something blew up!'});
      break;
  }
};

PHP


use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use GuzzleHttp\Psr7\Response;

function httpMethod(ServerRequestInterface $request): ResponseInterface
{
    switch ($request->getMethod()) {
        case 'GET':
            // Example: read request
            return new Response(
                200, // OK
                [],
                'Hello, World!' . PHP_EOL
            );
            break;
        case 'PUT':
            // Example: write request to a read-only resource
            return new Response(
                403, // Permission denied
                [],
                'Forbidden!' . PHP_EOL
            );
            break;
        default:
            // Example: request type not supported by the application
            $json_payload = json_encode([
                'error' => 'something blew up!'
            ]);
            return new Response(
                405, // Method not allowed
                ['Content-Type' => 'application/json'],
                $json_payload
            );
            break;
    }
}

Python

def hello_method(request):
    """ Responds to a GET request with "Hello world!". Forbids a PUT request.
    Args:
        request (flask.Request): The request object.
        <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
    """
    from flask import abort

    if request.method == 'GET':
        return 'Hello World!'
    elif request.method == 'PUT':
        return abort(403)
    else:
        return abort(405)

Ruby

require "functions_framework"
require "json"

FunctionsFramework.http "http_method" do |request|
  # The request parameter is a Rack::Request object.
  # See https://www.rubydoc.info/gems/rack/Rack/Request
  case request.request_method
  when "GET"
    status = 200
    body = "Hello World!"
  when "PUT"
    status = 403
    body = "Forbidden!"
  else
    status = 405
    body = '{"error":"Something blew up!"}'
  end

  # Return the response body as a Rack::Response object.
  ::Rack::Response.new body, status
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser