Skip to content

Instantly share code, notes, and snippets.

@chapimenge3
Last active December 4, 2022 17:57
Show Gist options
  • Save chapimenge3/9fd38418d8d8a2146bd3869e29eab846 to your computer and use it in GitHub Desktop.
Save chapimenge3/9fd38418d8d8a2146bd3869e29eab846 to your computer and use it in GitHub Desktop.
import os
import boto3
import json
TODO_TABLE = os.getenv('TODO_TABLE')
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(TODO_TABLE)
def create_todo(event, context):
'''
Create Todo Application in Dynamo DB
Params:
event: API Gateway Event
context: Lambda Context
Return:
response: API Gateway Response
response.body: JSON String
message: String
todoId: String
error: Boolean|String
'''
try:
body = event['body']
# check if the body is empty
if body is None:
raise Exception('Body is empty')
# check if the body is a string and convert it to a dict
if isinstance(body, str):
body = json.loads(body)
todo = body['todo']
# check if the todo is empty
if todo is None:
raise Exception('Todo is empty')
# check if todo is already in the table
if table.get_item(Key={'todo': todo}).get('Item') is not None:
raise Exception('Todo already exists')
# create todo
item = table.put_item(Item={'todo': todo, 'done': False})
# return todoId
response = {
'statusCode': 200,
'body': json.dumps({
'message': 'Todo created',
'todoId': item['todo'],
'error': False
})
}
return response
except Exception as e:
# return error
response = {
'statusCode': 400,
'body': json.dumps({
'message': str(e),
'error': True
})
}
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment