-
Notifications
You must be signed in to change notification settings - Fork 82
/
api_handler.py
62 lines (55 loc) · 1.77 KB
/
api_handler.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import boto3
import json
import os
import decimal
SFN_ARN = 'STEP_FUNCTION_ARN'
sfn = boto3.client('stepfunctions')
def lambda_handler(event, context):
print('EVENT:')
print(event)
data = json.loads(event['body'])
data['waitSeconds'] = int(data['waitSeconds'])
# Validation Checks
checks = []
checks.append('waitSeconds' in data)
checks.append(type(data['waitSeconds']) == int)
checks.append('preference' in data)
checks.append('message' in data)
if data.get('preference') == 'sms':
checks.append('phone' in data)
if data.get('preference') == 'email':
checks.append('email' in data)
# Check for any errors in validation checks
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, run the state machine and return a 200 code saying this is fine :)
else:
sfn.start_execution(
stateMachineArn=SFN_ARN,
input=json.dumps(data, cls=DecimalEncoder)
)
response = {
"statusCode": 200,
"headers": {"Access-Control-Allow-Origin":"*"},
"body": json.dumps(
{"Status": "Success"},
cls=DecimalEncoder
)
}
return response
# This is a workaround for: http://bugs.python.org/issue16535
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return int(obj)
return super(DecimalEncoder, self).default(obj)