I am trying to figure out how to parse the URL parameters in GCP cloud functions. I am trying to do pretty much what this answer does. Since the entry point to a HTTP GCP cloud function takes a request AFAIK. I can's figure out a way to have Flask parse the URL parameters like in the example I mentioned.
1 Answer
The URL parameters isn't very clear. If you talk about query parameter (the params after the ? in the url), you can simply take the getting started example
def hello_world(request):
request_json = request.get_json()
# Here the query parameters
if request.args and 'message' in request.args:
return request.args.get('message')
# Here it's in the post body in JSON
elif request_json and 'message' in request_json:
return request_json['message']
else:
return f'Hello World!'
If you talk about path parameter, you can rely on the view_args value
# Function code
def entrypoint(request):
return request.view_args, 200
# Test like that
> curl https://us-central1-<PROJECT ID>.cloudfunctions.net/<FUNCTION NAME>/test/to/path
> {"path":"test/to/path"}
However, the path parameter isn't split for you, and you need to handle it manually.
EDIT 1
I found how to hack Flask and use its URL processor. Here my working code sample
# Function code
from flask import Flask
def entrypoint(request):
path = request.view_args['path']
f = Flask("internal")
f.add_url_rule("/test/<string:id>", "entrypoint_internal")
r = f.test_request_context(path=path)
r.push()
path_value = r.request.view_args
r.pop()
return path_value, 200
# Test like that
> curl https://us-central1-<PROJECT ID>.cloudfunctions.net/<FUNCTION NAME>/test/path
> {"id":"path"}
1 Comment
guillaume blaquiere
And a new article inspired by you :) Thanks -> medium.com/google-cloud/…