-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_API_dynamodb.py
More file actions
56 lines (52 loc) · 1.68 KB
/
Copy pathlambda_API_dynamodb.py
File metadata and controls
56 lines (52 loc) · 1.68 KB
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
import json
import boto3
dynamodb = boto3.client('dynamodb')
def lambda_handler(event, context):
body = None
status_code = 200
headers = {
"Content-Type": "application/json"
}
try:
if event['routeKey'] == "DELETE /items/{id}":
response = dynamodb.delete_item(
TableName="crud-table",
Key={
'id': {'S': event['pathParameters']['id']}
}
)
body = f"Deleted item {event['pathParameters']['id']}"
elif event['routeKey'] == "GET /items/{id}":
response = dynamodb.get_item(
TableName="crud-table",
Key={
'id': {'S': event['pathParameters']['id']}
}
)
body = response
elif event['routeKey'] == "GET /items":
response = dynamodb.scan(TableName="crud-table")
body = response
elif event['routeKey'] == "PUT /items":
request_json = json.loads(event['body'])
response = dynamodb.put_item(
TableName="crud-table",
Item={
'id': {'S': request_json['id']},
'price': {'S': request_json['price']},
'name': {'S': request_json['name']}
}
)
body = f"Put item {request_json['id']}"
else:
raise Exception(f"Unsupported route: {event['routeKey']}")
except Exception as e:
status_code = 400
body = str(e)
finally:
body = json.dumps(body)
return {
'statusCode': status_code,
'body': body,
'headers': headers
}