Organiza tus páginas con colecciones Guarda y categoriza el contenido según tus preferencias.
Guía de inicio rápido: Crea e implementa una función de Cloud Functions (1ª gen.) mediante Google Cloud CLI

Crea e implementa una función de Cloud Functions (1ª gen.) mediante Google Cloud CLI

En esta página, se muestra cómo crear y, luego, implementar una función de Cloud Functions de primera generación mediante Google Cloud CLI.

Antes de comenzar

  1. Accede a tu cuenta de Google Cloud. Si eres nuevo en Google Cloud, crea una cuenta para evaluar el rendimiento de nuestros productos en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.
  2. En la página del selector de proyectos de Google Cloud Console, selecciona o crea un proyecto de Google Cloud.

    Ir al selector de proyectos

  3. Comprueba que la facturación esté habilitada en tu proyecto.

    Descubre cómo puedes habilitar la facturación

  4. Habilita las API de Cloud Functions and Cloud Build.

    Habilita las API

  5. En la página del selector de proyectos de Google Cloud Console, selecciona o crea un proyecto de Google Cloud.

    Ir al selector de proyectos

  6. Comprueba que la facturación esté habilitada en tu proyecto.

    Descubre cómo puedes habilitar la facturación

  7. Habilita las API de Cloud Functions and Cloud Build.

    Habilita las API

  8. Instala e inicializa la CLI de gcloud
  9. Actualiza los componentes de gcloud:
    gcloud components update
  10. ¿Necesitas un símbolo del sistema? Puedes usar Google Cloud Shell. Se trata de un entorno de línea de comandos que ya incluye Google Cloud CLI, por lo que no es necesario que lo instales. Google Cloud CLI también viene preinstalado en las máquinas virtuales de Google Compute Engine.

  11. Prepara tu entorno de desarrollo.

Obtenga el código de muestra

  1. Clona el repositorio de muestra en tu máquina local:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    Comienza a usarlo

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

  2. Ve al directorio que contiene el código de muestra de Cloud Functions, como sigue:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/helloworld/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloWorld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/get/

    PHP

    cd php-docs-samples/functions/helloworld_get/

  3. Ve el código de muestra:

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register an HTTP function with the Functions Framework that will be executed
    // when you make an HTTP request to the deployed function's endpoint.
    functions.http('helloGET', (req, res) => {
      res.send('Hello World!');
    });

    Python

    import functions_framework
    
    @functions_framework.http
    def hello_get(request):
        """HTTP Cloud Function.
        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>.
        Note:
            For more information on how Flask integrates with Cloud
            Functions, see the `Writing HTTP functions` page.
            <https://cloud.google.com/functions/docs/writing/http#http_frameworks>
        """
        return 'Hello World!'

    Comienza a usarlo

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    )
    
    // HelloGet is an HTTP Cloud Function.
    func HelloGet(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello, World!")
    }
    

    Java

    
    package functions;
    
    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;
    
    public class HelloWorld implements HttpFunction {
      // Simple function to return "Hello World"
      @Override
      public void service(HttpRequest request, HttpResponse response)
          throws IOException {
        BufferedWriter writer = response.getWriter();
        writer.write("Hello World!");
      }
    }

    C#

    using Google.Cloud.Functions.Framework;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    
    namespace HelloWorld;
    
    public class Function : IHttpFunction
    {
        public async Task HandleAsync(HttpContext context)
        {
            await context.Response.WriteAsync("Hello World!");
        }
    }

    Ruby

    require "functions_framework"
    
    FunctionsFramework.http "hello_get" do |_request|
      # The request parameter is a Rack::Request object.
      # See https://www.rubydoc.info/gems/rack/Rack/Request
    
      # 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 World!"
    end

    PHP

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

Implementa una función

Para implementar la función con un activador HTTP, ejecuta el siguiente comando en el directorio que contiene la función:

Node.js

gcloud functions deploy helloGET \
--runtime nodejs18 --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores para que la marca --runtime especifique tu versión preferida de Node.js:
  • nodejs18 (recomendada)
  • nodejs16
  • nodejs14
  • nodejs12
  • nodejs10

Python

gcloud functions deploy hello_get \
--runtime python311 --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores para que la marca --runtime especifique tu versión preferida de Python:
  • python311 (recomendada)
  • python310
  • python39
  • python38
  • python37

Go

gcloud functions deploy HelloGet \
--runtime go120 --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores en la marca --runtime para especificar tu versión preferida de Go:
  • go120 (recomendada)
  • go119
  • go118
  • go116
  • go113

Java

gcloud functions deploy java-helloworld \
--entry-point functions.HelloWorld \
--runtime java17 \
--memory 512MB --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores en la marca --runtime para especificar tu versión preferida de Go Java:
  • java17 (recomendada)
  • java11

C#

gcloud functions deploy csharp-helloworld \
--entry-point HelloWorld.Function \
--runtime dotnet6 --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores para que la marca --runtime especifique tu versión preferida de .NET:
  • dotnet6 (recomendada)
  • dotnet3

Ruby

gcloud functions deploy hello_get --runtime ruby30 --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores para que con la marca --runtime se especifique tu versión preferida de Ruby:
  • ruby30 (recomendada)
  • ruby32 (vista previa)
  • ruby27
  • ruby26

PHP

gcloud functions deploy helloGet --runtime php81 --trigger-http --allow-unauthenticated
Puedes usar los siguientes valores para que la marca --runtime especifique tu versión preferida de PHP:
  • php81 (recomendada)
  • php74

La marca --allow-unauthenticated te permite acceder a la función sin autenticación. Para solicitar la autenticación, omite la marca.

Prueba la función

  1. Cuando la función termine de implementarse, toma nota de la propiedad httpsTrigger's url o búscala con el siguiente comando:

    Node.js

    gcloud functions describe helloGET

    Python

    gcloud functions describe hello_get

    Go

    gcloud functions describe HelloGet

    Java

    gcloud functions describe java-helloworld

    C#

    gcloud functions describe csharp-helloworld

    Ruby

    gcloud functions describe hello_get

    PHP

    gcloud functions describe helloGet

    Se verá de la siguiente manera:

    Node.js

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET

    Python

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    Go

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloGet

    Java

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/java-helloworld

    C#

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/csharp-helloworld

    Ruby

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    PHP

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGet

  2. Visita esta URL en tu navegador. Deberías ver un mensaje de Hello World!.

Borra la función

Si deseas borrar la función, ejecuta el siguiente comando:

Node.js

gcloud functions delete helloGET 

Python

gcloud functions delete hello_get 

Go

gcloud functions delete HelloGet 

Java

gcloud functions delete java-helloworld 

C#

gcloud functions delete csharp-helloworld 

Ruby

gcloud functions delete hello_get 

PHP

gcloud functions delete helloGet 

¿Qué sigue?

Consulta la guía relevante Tu primera función para el entorno de ejecución que elijas, de modo que aprendas a configurar tu entorno de desarrollo, crear una nueva función desde cero, especificar dependencias, implementar tu función, probar tu función y ver los registros. Ten en cuenta que estas guías son solo para Cloud Functions (1st gen):