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