Send HTTP requests
Stay organized with collections
Save and categorize content based on your preferences.
Shows how to make an HTTP request from a Cloud Function.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis page demonstrates how to make an HTTP request from a Cloud Function using various programming languages.\u003c/p\u003e\n"],["\u003cp\u003eCode examples are provided in C#, Go, Java, Node.js, PHP, Python, and Ruby, each showcasing a method for making an external HTTP request.\u003c/p\u003e\n"],["\u003cp\u003eThe examples highlight the use of HTTP client libraries within Cloud Functions to interact with external URLs, such as fetching content from "http://example.com" or "https://example.com".\u003c/p\u003e\n"],["\u003cp\u003eAuthentication to Cloud Run functions is emphasized, recommending the setup of Application Default Credentials for secure local development environments, with a link provided for more information.\u003c/p\u003e\n"]]],[],null,["Shows how to make an HTTP request from a Cloud Function.\n\nCode sample \n\nC#\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n using Google.Cloud.Functions.Framework;\n using Google.Cloud.Functions.Hosting;\n using Microsoft.AspNetCore.Hosting;\n using Microsoft.AspNetCore.Http;\n using https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Memorystore.V1Beta/latest/Microsoft.Extensions.DependencyInjection.html;\n using System.Net.Http;\n using System.Threading.Tasks;\n\n namespace SendHttpRequest;\n\n // Dependency injection configuration, executed during server startup.\n public class Startup : FunctionsStartup\n {\n public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)\n {\n // Make an HttpClient available to our function via dependency injection.\n // There are many options here; see\n // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests\n // for more details.\n services.AddHttpClient\u003cIHttpFunction, Function\u003e();\n }\n }\n\n // Function, decorated with the FunctionsStartup attribute to specify the startup class\n // for dependency injection.\n [FunctionsStartup(typeof(Startup))]\n public class Function : IHttpFunction\n {\n private readonly HttpClient _httpClient;\n\n public Function(HttpClient httpClient) =\u003e\n _httpClient = httpClient;\n\n public async Task HandleAsync(HttpContext context)\n {\n string url = \"http://example.com\";\n using (HttpResponseMessage clientResponse = await _httpClient.GetAsync(url, context.RequestAborted))\n {\n await context.Response.WriteAsync(\n $\"Received code '{(int) clientResponse.StatusCode}' from URL '{url}'.\",\n context.RequestAborted);\n }\n }\n }\n\nGo\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package http provides a set of HTTP Cloud Functions samples.\n package http\n\n import (\n \t\"fmt\"\n \t\"net/http\"\n \t\"time\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n )\n\n var urlString = \"https://example.com\"\n\n // client is used to make HTTP requests with a 10 second timeout.\n // http.Clients should be reused instead of created as needed.\n var client = &http.Client{\n \tTimeout: 10 * time.Second,\n }\n\n func init() {\n \tfunctions.HTTP(\"MakeRequest\", MakeRequest)\n }\n\n // MakeRequest is an example of making an HTTP request. MakeRequest uses a\n // single http.Client for all requests to take advantage of connection\n // pooling and caching. See https://godoc.org/net/http#Client.\n func MakeRequest(w http.ResponseWriter, r *http.Request) {\n \tresp, err := client.Get(urlString)\n \tif err != nil {\n \t\thttp.Error(w, \"Error making request\", http.StatusInternalServerError)\n \t\treturn\n \t}\n \tif resp.StatusCode != http.StatusOK {\n \t\tmsg := fmt.Sprintf(\"Bad StatusCode: %d\", resp.StatusCode)\n \t\thttp.Error(w, msg, http.StatusInternalServerError)\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"ok\")\n }\n\nJava\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.HttpFunction;\n import com.google.cloud.functions.HttpRequest;\n import com.google.cloud.functions.HttpResponse;\n import java.io.IOException;\n import java.io.PrintWriter;\n import java.net.URI;\n import java.net.http.HttpClient;\n import java.net.http.HttpResponse.BodyHandlers;\n import java.time.Duration;\n\n public class SendHttpRequest implements HttpFunction {\n\n // Create a client with some reasonable defaults. This client can be reused for multiple requests.\n // (java.net.httpClient also pools connections automatically by default.)\n private static HttpClient client =\n HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();\n\n @Override\n public void service(HttpRequest request, HttpResponse response)\n throws IOException, InterruptedException {\n // Create a GET sendHttpRequest to \"http://example.com\"\n String url = \"http://example.com\";\n var getRequest = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)).GET().build();\n\n // Send the sendHttpRequest using the client\n var getResponse = client.send(getRequest, BodyHandlers.ofString());\n\n // Write the results to the output:\n var writer = new PrintWriter(response.getWriter());\n writer.printf(\"Received code '%s' from url '%s'.\", getResponse.statusCode(), url);\n }\n }\n\nNode.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const fetch = require('node-fetch');\n const functions = require('@google-cloud/functions-framework');\n\n /**\n * HTTP Cloud Function that makes an HTTP request\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('makeRequest', async (req, res) =\u003e {\n const url = 'https://example.com'; // URL to send the request to\n const externalRes = await fetch(url);\n res.sendStatus(externalRes.ok ? 200 : 500);\n });\n\nPHP\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n use Psr\\Http\\Message\\ServerRequestInterface;\n use Psr\\Http\\Message\\ResponseInterface;\n use GuzzleHttp\\Client;\n use GuzzleHttp\\Psr7\\Response;\n\n function makeRequest(ServerRequestInterface $request): ResponseInterface\n {\n // This sample uses the GuzzleHTTP client\n // See its documentation for usage information\n // https://docs.guzzlephp.org/en/stable/\n\n // Specify the URL to send requests to\n $client = new Client([\n 'base_uri' =\u003e 'https://example.com',\n ]);\n\n // Send the request\n $url_response = $client-\u003eget('/');\n\n $function_response = new Response(\n $url_response-\u003egetStatusCode(),\n [], // headers\n '' // body\n );\n\n return $function_response;\n }\n\nPython\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import functions_framework\n\n\n @functions_framework.http\n def make_request(request):\n \"\"\"\n HTTP Cloud Function that makes another HTTP request.\n Args:\n request (flask.Request): The request object.\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Request\u003e\n Returns:\n The response text, or any set of values that can be turned into a\n Response object using `make_response`\n \u003chttp://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response\u003e.\n \"\"\"\n import requests\n\n # The URL to send the request to\n url = \"http://example.com\"\n\n # Process the request\n response = requests.get(url)\n response.raise_for_status()\n return \"Success!\"\n\nRuby\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n require \"functions_framework\"\n require \"net/http\"\n\n FunctionsFramework.http \"concepts_requests\" do |_request|\n url = \"example.com\"\n response = Net::HTTP.get_response url, \"/\"\n \"Received code: #{response.code} from url: #{url}\"\n end\n\nWhat's next\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]