Create and deploy an HTTP Cloud Run function with Python

This guide takes you through the process of writing a Cloud Run function using the Python runtime. There are two types of Cloud Run functions:

  • An HTTP function, which you invoke from standard HTTP requests.
  • 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.

For more detail, read writing HTTP functions and writing event-driven functions.

Before you begin

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions, Cloud Build, Artifact Registry, Cloud Run, and Cloud Logging APIs.

    Enable the APIs

  8. Install and initialize the gcloud CLI.
  9. Update and install gcloud components with the following command.
    gcloud components update
  10. Prepare your development environment.

    Go to the Python setup guide

Create your function

  1. Create a directory on your local system for the function code:

    Linux or Mac OS X

    mkdir ~/helloworld
    cd ~/helloworld
    

    Windows

    mkdir %HOMEPATH%\helloworld
    cd %HOMEPATH%\helloworld
    
  2. Create a main.py file in the helloworld directory with the following contents:

    
    import functions_framework
    
    
    from markupsafe import escape
    
    @functions_framework.http
    def hello_http(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>.
        """
        request_json = request.get_json(silent=True)
        request_args = request.args
    
        if request_json and "name" in request_json:
            name = request_json["name"]
        elif request_args and "name" in request_args:
            name = request_args["name"]
        else:
            name = "World"
        return f"Hello {escape(name)}!"
    
    

    This example function takes a name supplied in the HTTP request and returns a greeting, or "Hello World!" when no name is supplied.

Specify dependencies

Dependencies in Python are managed with pip and expressed in a metadata file called requirements.txt. This file must be in the same directory as the main.py file that contains your function code.

  1. Create a requirements.txt file in the helloworld directory with the following contents:

      # An example requirements file. If your function has other dependencies,
      # add them below
      functions-framework==3.*
    

Build and test your function locally

To build and test your function locally before deploying it:

  1. Run the package installer for Python, pip, to install your package's dependencies:

    pip3 install -r requirements.txt
    PATH=$PATH:~/.local/bin
    
  2. Run your function locally with the Functions Framework:

    functions-framework-python --target hello_http
    
  3. Test your function by visiting http://localhost:8080 in a browser or by running curl localhost:8080 from another window.

    See Sending requests to local functions for more detail.

Deploy your function

To deploy your function, run the following command in the helloworld directory:

  gcloud functions deploy python-http-function \
    --gen2 \
    --runtime=python312 \
    --region=REGION \
    --source=. \
    --entry-point=hello_http \
    --trigger-http \
    --allow-unauthenticated

Replace REGION with the name of the Google Cloud region where you want to deploy your function (for example, us-west1).

The optional --allow-unauthenticated flag lets you reach your function without authentication.

Test your deployed function

  1. After the function deploys, note the uri property from the output of the gcloud functions deploy command, or retrieve it with the following command:

    gcloud functions describe python-http-function \
      --region=REGION
    

    Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

  2. Visit this URL in your browser. The function returns a "Hello World!" message.

View your function's logs

View the logs with the command-line tool

You can review your function's logs with the Cloud Logging UI or via the Google Cloud CLI.

To view logs for your function with the gcloud CLI, use the logs read command:

  gcloud functions logs read \
    --gen2 \
    --limit=10 \
    --region=REGION \
    python-http-function

Replace REGION with the name of the Google Cloud region where you deployed your function (for example, us-west1).

The output resembles the following:

LEVEL: I
NAME: hello-http
TIME_UTC: 2023-06-01 19:33:42.991
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "hello__http-1" on port 8080.

LEVEL: I
NAME: hello-http
TIME_UTC: 2023-06-01 19:33:41.933
LOG:

LEVEL: I
NAME: hello-http
TIME_UTC: 2023-06-01 19:33:26.475
LOG: Default STARTUP TCP probe succeeded after 1 attempt for container "hello__http-1" on port 8080.

View logs with the logging dashboard

To view the logs for your function with the logging dashboard, open the Cloud Run functions Overview page and click the name of your function from the list, then click the Logs tab.