Send HTTP requests

Shows how to make an HTTP request from a Cloud Function.

Documentation pages that include this code sample

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

Code sample


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

namespace SendHttpRequest
    // Dependency injection configuration, executed during server startup.
    public class Startup : FunctionsStartup
        public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
            // Make an HttpClient available to our function via dependency injection.
            // There are many options here; see
            // for more details.
            services.AddHttpClient<IHttpFunction, Function>();

    // Function, decorated with the FunctionsStartup attribute to specify the startup class
    // for dependency injection.
    public class Function : IHttpFunction
        private readonly HttpClient _httpClient;

        public Function(HttpClient httpClient) =>
            _httpClient = httpClient;

        public async Task HandleAsync(HttpContext context)
            string url = "";
            using (HttpResponseMessage clientResponse = await _httpClient.GetAsync(url))
                await context.Response.WriteAsync($"Received code '{(int) clientResponse.StatusCode}' from URL '{url}'.");


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

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

namespace {
// Use Boost.Beast to illustrate making HTTP requests, return the status code.
unsigned int make_http_request(std::string const& host);
}  // namespace

gcf::HttpResponse concepts_request(gcf::HttpRequest /*request*/) {  // NOLINT
  std::string const host = "";
  auto const code = make_http_request(host);
  return gcf::HttpResponse{}.set_payload(
      "Received code " + std::to_string(code) + " from " + host);


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

import (

var urlString = ""

// client is used to make HTTP requests with a 10 second timeout.
// http.Clients should be reused instead of created as needed.
var client = &http.Client{
	Timeout: 10 * time.Second,

// MakeRequest is an example of making an HTTP request. MakeRequest uses a
// single http.Client for all requests to take advantage of connection
// pooling and caching. See
func MakeRequest(w http.ResponseWriter, r *http.Request) {
	resp, err := client.Get(urlString)
	if err != nil {
		http.Error(w, "Error making request", http.StatusInternalServerError)
	if resp.StatusCode != http.StatusOK {
		msg := fmt.Sprintf("Bad StatusCode: %d", resp.StatusCode)
		http.Error(w, msg, http.StatusInternalServerError)
	fmt.Fprintf(w, "ok")


import java.time.Duration;

public class SendHttpRequest implements HttpFunction {

  // Create a client with some reasonable defaults. This client can be reused for multiple requests.
  // ( also pools connections automatically by default.)
  private static HttpClient client =

  public void service(HttpRequest request, HttpResponse response)
      throws IOException, InterruptedException {
    // Create a GET sendHttpRequest to ""
    String url = "";
    var getRequest =;

    // Send the sendHttpRequest using the client
    var getResponse = client.send(getRequest, BodyHandlers.ofString());

    // Write the results to the output:
    var writer = new PrintWriter(response.getWriter());
    writer.printf("Received code '%s' from url '%s'.", getResponse.statusCode(), url);


const fetch = require('node-fetch');

 * HTTP Cloud Function that makes an HTTP request
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
exports.makeRequest = async (req, res) => {
  const url = ''; // URL to send the request to
  const externalRes = await fetch(url);
  res.sendStatus(externalRes.ok ? 200 : 500);


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

function makeRequest(ServerRequestInterface $request): ResponseInterface
    // This sample uses the GuzzleHTTP client
    // See its documentation for usage information

    // Specify the URL to send requests to
    $client = new Client([
        'base_uri' => '',

    // Send the request
    $url_response = $client->get('/');

    $function_response = new Response(
        [], // headers
        ''  // body

    return $function_response;


def make_request(request):
    HTTP Cloud Function that makes another HTTP request.
        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`
    import requests

    # The URL to send the request to
    url = ''

    # Process the request
    response = requests.get(url)
    return 'Success!'


require "functions_framework"
require "net/http"

FunctionsFramework.http "concepts_requests" do |_request|
  url = ""
  response = Net::HTTP.get_response url, "/"
  "Received code: #{response.code} from url: #{url}"

What's next

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