-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_lambda.py
45 lines (36 loc) · 1.59 KB
/
api_lambda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import boto3, json, os, decimal
SM_ARN = 'arn:aws:states:us-east-1:484907511744:stateMachine:PetCuddleOTron'
sm = boto3.client('stepfunctions')
def lambda_handler(event, context):
# Print event data to logs
print("Received event: " + json.dumps(event))
# Load data coming from APIGateway
data = json.loads(event['body'])
data['waitSeconds'] = int(data['waitSeconds'])
# Sanity check that all of the parameters we need have come through from API gateway
# Mixture of optional and mandatory ones
checks = []
checks.append('waitSeconds' in data)
checks.append(type(data['waitSeconds']) == int)
checks.append('message' in data)
# if any checks fail, return error to API Gateway to return to client
if False in checks:
response = {
"statusCode": 400,
"headers": {"Access-Control-Allow-Origin":"*"},
"body": json.dumps( { "Status": "Success", "Reason": "Input failed validation" }, cls=DecimalEncoder )
}
# If none, start the state machine execution and inform client of 2XX success :)
else:
sm.start_execution( stateMachineArn=SM_ARN, input=json.dumps(data, cls=DecimalEncoder) )
response = {
"statusCode": 200,
"headers": {"Access-Control-Allow-Origin":"*"},
"body": json.dumps( {"Status": "Success"}, cls=DecimalEncoder )
}
return response
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return int(obj)
return super(DecimalEncoder, self).default(obj)