Skip to content

Instantly share code, notes, and snippets.

@shapi78
Last active April 4, 2024 13:44
Show Gist options
  • Save shapi78/33b2e1489a46a640ca1bef2deb462ac7 to your computer and use it in GitHub Desktop.
Save shapi78/33b2e1489a46a640ca1bef2deb462ac7 to your computer and use it in GitHub Desktop.
GCP API Gateway setup

Create a cloud function: Go to Cloud Functions by searching for “Cloud Functions” in search bar:

  • Press “create function” button and fill up the form:

Environment: 2nd gen Function name: Region: Choose “Allow unauthorized invocations”

Press “Next” and lets write the code for the function. Lets pick the code language that we use:

Next, write you code and correct the entry point. The code i used is taking 2 numbers and sum them up:



@functions_framework.http
def calculate(request):
   """HTTP Cloud Function to perform calculation on two numbers.
   Args:
       request (flask.Request): The request object.
   Returns:
       The result of the calculation as JSON.
   """
   request_json = request.get_json(silent=True)


   if request_json and 'num1' in request_json and 'num2' in request_json:
       num1 = request_json['num1']
       num2 = request_json['num2']
   else:
       return {'error': 'Please provide num1 and num2 in the request body as JSON.'}, 400
  
   try:
       result = float(num1) + float(num2)
       return {'result': result}, 200
   except ValueError:
       return {'error': 'Invalid input. Please provide valid numbers.'}, 400
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment