35
loading...
This website collects cookies to deliver better user experience
a
and b
with both being a number, they will get back the result of the two multiplied. To do this, we will be using AWS's API Gateway to handle the endpoints. Let's get started!def lambda_handler(event, context):
return 'Something'
event
parameter. This parameter contains any data sent to the Lambda function. If we were triggering the Lambda function manually, we would use the event
variable as an exact representation of the data.event
would be equal to 16
.event
variable for a Lambda triggered by an endpoint, it would look like:{
"version": "2.0",
"routeKey": "GET /testFunction",
"rawPath": "/testFunction",
"rawQueryString": "",
"headers": {},
"requestContext": {},
"body": "{\"exampleJSONKey\": \"Random text\"}",
"isBase64Encoded": false
}
event['body']
but we will need to decode the JSON. This will look like this:import json
def lambda_handler(event, context):
body = json.loads(event['body'])
return 'Something'
a
and b
to be multiplied together. So, we can add then use these in the return like this:import json
def lambda_handler(event, context):
body = json.loads(event['body'])
return body['a'] * body['b']
import json
def lambda_handler(event, context):
body = json.loads(event['body'])
if not is_numerical(body['a']) or not is_numerical(body['b']):
return 'One or both of the values are not a number'
return body['a'] * body['b']
def is_numerical(value):
""""Checks if value is an int or float."""
return isinstance(value, int) or isinstance(value, float)
import json
def lambda_handler(event, context):
body = json.loads(event['body'])
if not is_numerical(body['a']) or not is_numerical(body['b']):
return {
'error': 'One or both of the values are not a number'
}
return {
'result': body['a'] * body['b']
}
def is_numerical(value):
""""Checks if value is an int or float."""
return isinstance(value, int) or isinstance(value, float)
a
and b
. So, let's add one last conditional to check that:import json
def lambda_handler(event, context):
body = json.loads(event['body'])
if 'a' not in body or 'b' not in body:
return {
'error': 'You must provide keys for both "a" and "b"'
}
if not is_numerical(body['a']) or not is_numerical(body['b']):
return {
'error': 'One or both of the values are not a number'
}
return {
'result': body['a'] * body['b']
}
def is_numerical(value):
""""Checks if value is an int or float."""
return isinstance(value, int) or isinstance(value, float)