Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Crea e implementa una función Cloud Run Function HTTP con Ruby (1ª gen.)
En esta guía, se explica el proceso para escribir una Cloud Run Function mediante el entorno de ejecución de Ruby. Existen dos tipos de Cloud Run Functions:
Una función de HTTP que se invoca a partir de solicitudes HTTP estándar.
La otra es una función controlada por eventos que se usa para manejar los eventos de la infraestructura de tu nube, como mensajes en un tema de Cloud Pub/Sub o cambios en un bucket de Cloud Storage.
En el ejemplo, se muestra cómo crear una función de HTTP simple.
Antes de comenzar
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Crea un archivo app.rb en el directorio helloworld con el siguiente contenido:
require"functions_framework"require"cgi"require"json"FunctionsFramework.http"hello_http"do|request|# The request parameter is a Rack::Request object.# See https://www.rubydoc.info/gems/rack/Rack/Requestname=request.params["name"]||(request.body.rewind && JSON.parse(request.body.read)["name"]rescuenil)||"World"# 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_htmlname}!"end
Esta función de ejemplo toma un nombre proporcionado en la solicitud HTTP y muestra un saludo o “Hello World!” cuando no se proporciona ningún nombre.
Especificar dependencias
Las dependencias en Ruby se administran con bundler y se expresan en un archivo llamado Gemfile.
Cuando implementas tu función, Cloud Run Functions descargan y, luego, instalan
las dependencias declaradas en Gemfile y Gemfile.lock con bundler.
El Gemfile enumera los paquetes que requiere tu función, junto con las restricciones de las versiones opcionales. Para una Cloud Run Function, uno de estos paquetes debe ser la gema functions_framework.
Para este ejercicio, crea un archivo llamado Gemfile en el mismo directorio que el archivo app.rb que contiene el código de tu función, con el siguiente contenido:
Ejecuta el siguiente comando para instalar la gema functions_framework y otras dependencias:
bundleinstall
Compila y prueba de manera local
Antes de implementar la función, puedes compilarla y probarla de forma local.
Ejecuta el siguiente comando para usar el ejecutable functions-framework-ruby para iniciar un servidor web local que ejecute tu función hello_http:
bundleexecfunctions-framework-ruby--targethello_http# ...starts the web server in the foreground
Si la función se compila correctamente, mostrará la URL que puedes visitar en tu navegador web para ver la función en acción: http://localhost:8080/. Deberías ver un mensaje Hello World!.
Como alternativa, puedes enviar solicitudes a esta función mediante curl desde otra ventana de terminal:
curllocalhost:8080# Output: Hello World!
Consulta también Testing Functions en la documentación Functions Framework de Ruby.
Implementa la función
Ejecuta el siguiente comando en el directorio helloworld para implementar la función con un activador HTTP:
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-10 (UTC)"],[[["\u003cp\u003eThis guide details how to create and deploy an HTTP Cloud Run function using the Ruby runtime environment, enabling it to be invoked via standard HTTP requests.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves creating an \u003ccode\u003eapp.rb\u003c/code\u003e file with the function code, which, in this example, generates a personalized greeting based on a name provided in the HTTP request, defaulting to "Hello World!".\u003c/p\u003e\n"],["\u003cp\u003eDependencies for the Ruby Cloud Run function are managed using Bundler and a \u003ccode\u003eGemfile\u003c/code\u003e, where \u003ccode\u003efunctions_framework\u003c/code\u003e gem is required, and they are installed during the deployment.\u003c/p\u003e\n"],["\u003cp\u003eBefore deploying, the function can be built and tested locally using \u003ccode\u003efunctions-framework-ruby\u003c/code\u003e, allowing verification of its behavior before it goes live.\u003c/p\u003e\n"],["\u003cp\u003eThe function is deployed via the \u003ccode\u003egcloud functions deploy\u003c/code\u003e command, which can include the \u003ccode\u003e--allow-unauthenticated\u003c/code\u003e flag to permit access without requiring prior authentication.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Create and deploy an HTTP Cloud Run function by using Ruby\n\nCreate and deploy an HTTP Cloud Run function by using Ruby (1st gen)\n====================================================================\n\nThis guide takes you through the process of writing a Cloud Run function\nusing the Ruby runtime. There are two types of Cloud Run functions:\n\n- An HTTP function, which you invoke from standard HTTP requests.\n- An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Pub/Sub topic, or changes in a Cloud Storage bucket.\n\nThe sample shows how to create a simple HTTP function.\n| **Learn more** : For more details, read about [HTTP functions](/functions/1stgendocs/writing/write-http-functions) and [event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions).\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n1. [Install and initialize the gcloud CLI](/sdk/docs).\n2. Update and install `gcloud` components: \n\n ```bash\n gcloud components update\n ```\n| **Note** : Need a command prompt? You can use [Cloud Shell](https://console.cloud.google.com/?cloudshell=true). Cloud Shell is a command line environment that already includes the Google Cloud CLI, so you don't need to install it. The Google Cloud CLI also comes preinstalled on Compute Engine Virtual Machines.\n3. Prepare your development environment.\n [Go to the Ruby setup guide](/ruby/docs/setup)\n\nCreate a function\n-----------------\n\n1. Create a directory on your local system for the function code:\n\n ### Linux or Mac OS X\n\n mkdir ~/helloworld\n cd ~/helloworld\n\n ### Windows\n\n mkdir %HOMEPATH%\\helloworld\n cd %HOMEPATH%\\helloworld\n\n2. Create an `app.rb` file in the `helloworld` directory with the\n following contents:\n\n require \"functions_framework\"\n require \"cgi\"\n require \"json\"\n\n FunctionsFramework.http \"hello_http\" do |request|\n # The request parameter is a Rack::Request object.\n # See https://www.rubydoc.info/gems/rack/Rack/Request\n name = request.params[\"name\"] ||\n (request.body.rewind && JSON.parse(request.body.read)[\"name\"] rescue nil) ||\n \"World\"\n # Return the response body as a string.\n # You can also return a Rack::Response object, a Rack response array, or\n # a hash which will be JSON-encoded into a response.\n \"Hello #{CGI.escape_html name}!\"\n end\n\n This example function takes a name supplied in the HTTP request and returns\n a greeting, or \"Hello World!\" when no name is supplied.\n | **Note:** Cloud Run functions looks for deployable functions in `app.rb` by default. Use the [`--source`](/sdk/gcloud/reference/functions/deploy#--source) flag when [deploying your function using `gcloud`](#deploy_the_function) to specify a different directory containing an `app.rb` file.\n\nSpecify dependencies\n--------------------\n\nDependencies in Ruby are managed with [bundler](https://bundler.io) and expressed in a file called\n`Gemfile`.\n\nWhen you deploy your function, Cloud Run functions downloads and installs the\ndependencies declared in the `Gemfile` and `Gemfile.lock` using `bundler`.\n\nThe `Gemfile` lists the packages required by your function, along with any\noptional version constraints. For a Cloud Run function, one of these\npackages must be the `functions_framework` gem.\n\nFor this exercise, create a file named `Gemfile` in the same directory as the\n`app.rb` file that contains your function code, with the following contents: \n\n```\nsource \"https://rubygems.org\"\n\ngem \"functions_framework\", \"~\u003e 0.7\"\n```\n\nRun the following command to install the `functions_framework` gem and other\ndependencies: \n\n bundle install\n\n| **Learn more** : For more details, read about [specifying dependencies](/functions/1stgendocs/writing/specifying-dependencies-ruby).\n\nBuild and test locally\n----------------------\n\nBefore deploying the function, you can build and test it locally.\nRun the following command to use the `functions-framework-ruby` executable to\nstart a local web server running your `hello_http` function: \n\n bundle exec functions-framework-ruby --target hello_http\n # ...starts the web server in the foreground\n\nIf the function builds successfully, it displays the URL you can visit in your\nweb browser to see the function in action:\n`http://localhost:8080/`. You should see a `Hello World!` message.\n\nAlternatively, you can send requests to this function using `curl` from another\nterminal window: \n\n curl localhost:8080\n # Output: Hello World!\n\nSee [Testing Functions](https://github.com/GoogleCloudPlatform/functions-framework-ruby#documentation)\nin the Ruby Functions Framework documentation.\n\nDeploy the function\n-------------------\n\nTo deploy the function with an HTTP trigger, run the following\ncommand in the `helloworld` directory: \n\n gcloud functions deploy hello_http --no-gen2 --runtime ruby33 --trigger-http --allow-unauthenticated\n\nThe `--allow-unauthenticated` flag lets you reach the function\n[without authentication](/functions/1stgendocs/securing/managing-access-iam#allowing_unauthenticated_http_function_invocation).\nTo require\n[authentication](/functions/1stgendocs/securing/authenticating#developers), omit the\nflag.\n| **Learn more** : For more details, read about [deploying Cloud Run functions](/functions/1stgendocs/deploy#basics).\n\nTest the deployed function\n--------------------------\n\n1. When the function finishes deploying, take note of the `httpsTrigger.url`\n property or find it using the following command:\n\n gcloud functions describe hello_http\n\n It should look like this: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http\n ```\n2. Visit this URL in your browser. You should see a \"Hello World!\" message.\n\n Try passing a name in the HTTP request, for example by using the following\n URL: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME\n ```\n\n You should see the message \"Hello \u003cvar translate=\"no\"\u003eNAME\u003c/var\u003e!\"\n\nView logs\n---------\n\nYou can view Cloud Run functions logs in the Cloud Logging UI or through the\nGoogle Cloud CLI.\n\n### View logs with the command-line tool\n\nTo view logs for your function with the gcloud CLI, use the\n[`logs read`](/sdk/gcloud/reference/functions/logs/read) command, followed by\nthe name of the function: \n\n```bash\ngcloud functions logs read hello_http\n```\n\nThe output should resemble the following: \n\n```bash\nLEVEL NAME EXECUTION_ID TIME_UTC LOG\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200\n```\n| **Note:** There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.\n\n### View logs in the Logging dashboard\n\nYou can also view logs for Cloud Run functions from the\n[Google Cloud console](https://console.cloud.google.com/project/_/logs?service=cloudfunctions.googleapis.com).\n| **Learn more** : For more details, read about [writing, viewing, and responding to logs](/functions/1stgendocs/monitoring/logging)."]]