pinglock
pinglock

Reputation: 1281

Passing Variables To Google Cloud Functions

I've just finished writing a Google Cloud Function in the Beta Python 3.7 runtime with an HTTP trigger. Now I'm trying to figure out how to pass a string variable to my function when calling it. I've read the documentation but I haven't found anything on this.

My trigger resembles:

https://us-central1-*PROJECT_ID*.cloudfunctions.net/*FUNCTION_NAME*

Am I misunderstanding how Cloud Functions work? Can you even pass variables to them?

Upvotes: 29

Views: 31385

Answers (1)

Dustin Ingram
Dustin Ingram

Reputation: 21580

You'd pass variables to the function the same way you'd pass variables to any URL:

1. Via a GET with query parameters:

def test(request):
    name = request.args.get('name')
    return f"Hello {name}"
$ curl -X GET https://us-central1-<PROJECT>.cloudfunctions.net/test?name=World
Hello World

2. Via a POST with a form:

def test(request):
    name = request.form.get('name')
    return f"Hello {name}"
$ curl -X POST https://us-central1-<PROJECT>.cloudfunctions.net/test -d "name=World"
Hello World

3. Via a POST with JSON:

def test(request):
    name = request.get_json().get('name')
    return f"Hello {name}"
$ curl -X POST https://us-central1-<PROJECT>.cloudfunctions.net/test -d '{"name":"World"}'
Hello World

More details can be found here: https://cloud.google.com/functions/docs/writing/http

Upvotes: 59

Related Questions