Test Python Google Cloud Functions locally

Update

Please, use the official emulator and serving framework from GCP https://github.com/GoogleCloudPlatform/functions-framework-python

You can install it with

pip install functions-framework

Deprecated

Based on Dustin's answer I've developed a package to serve as emulator:

pip install gcp-functions-emulator

Given you want to serve the following function

# mycloudfunction.py
def api(request):
  return 'important data'

To emulate we have to call it like so:

gcpfemu <path/to/file.py> <function_name>

For example, with the code above we will call it:

gcpfemu mycloudfunction.py api

And to access the data we can use for example curl:

curl localhost:5000/api
> important data

You can use the Functions Framework for Python to run the function locally.

Given a function in a file named main.py like so:

def my_function(request):
    return 'Hello World'

You can do:

$ pip install functions-framework
$ functions-framework --target my_function

Which will start a local development server at http://localhost:8080.

To invoke it locally for an HTTP function:

$ curl http://localhost:8080

For a background function with non-binary data:

$ curl -d '{"data": {"hi": "there"}}' -X POST \
-H "Content-Type: application/json" \
http://localhost:8080

For a background function with binary data:

$ curl -d "@binary_file.file" -X POST \
-H "Ce-Type: true" \
-H "Ce-Specversion: true" \
-H "Ce-Source: true" \
-H "Ce-Id: true" \
-H "Content-Type: application/json" \
http://localhost:8080