Building a Serverless REST API on AWS in Python

Aloha!

  1. API Gateway for deploying and serving HTTP RESTful endpoints.
  2. AWS Lambda to run code without provisioning or managing servers.
  3. DynamoDB, the NoSQL amazon database, to Store/Delete/Read JSON records.
  1. Select Permissions inside the Lambda function you’ve just created.
  2. Select the Role Name which was created by AWS for you.
import json
import boto3
from datetime import datetime
def lambda_handler(event, context):

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('REST')

eventDateTime = (datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
userId = event['Id']
firstName = event['FirstName']
lastName = event['LastName']
age = event['Age']
hobbies = event['Hobbies']

try:

table.put_item(
Item={
'eventDateTime': eventDateTime,
'Id': userId,
'FirstName': firstName,
'LastName': lastName,
'Age': age,
'Hobbies': hobbies
}
)

return {
'statusCode': 200,
'body': json.dumps('Succesfully inserted the user info!')
}
except:
return {
'statusCode': 400,
'body': json.dumps('Error saving the user info')
}
{
"Id": "a1",
"FirstName": "Robert",
"LastName": "Downy",
"Age": 45,
"Hobbies": [
"Movies",
"Books"
]
}
{
"Id": "a2",
"FirstName": "Jack",
"LastName": "King",
"Age": 30,
"Hobbies": [
"Sports",
"Arts"
]
}

GET Lambda Function:

import json
import boto3
def lambda_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('REST')
response = table.scan()
return {
'statusCode': 200,
'body': response['Items']
}

DELETE Lambda Function:

import json
import boto3
def lambda_handler(event, context):

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('REST')

userId = event['Id']
firstName = event['FirstName']

try:
response = table.delete_item(
Key={
'Id': userId,
'FirstName': firstName
}
)
return response
except Exception as e:
print(e)
return {
'statusCode': 400,
'body': json.dumps('Error deleting the user info')
}
{
"Id": "a2",
"FirstName": "Jack"
}

Eureka!

We have done it!

Self improvement task:

  1. Try to improve the POST operation by using the following payload to add multiple records at once!
[
{
"Id": "a1",
"FirstName": "Robert",
"LastName": "Downy",
"Age": 45,
"Hobbies": [
"Movies",
"Books"
]
},
{
"Id": "a2",
"FirstName": "Jack",
"LastName": "King",
"Age": 30,
"Hobbies": [
"Sports",
"Arts"
]
},
{
"Id": "a3",
"FirstName": "Mary",
"LastName": "Jane",
"Age": 25,
"Hobbies": [
"Racing",
"Cooking"
]
},
{
"Id": "a4",
"FirstName": "Christine",
"LastName": "Price",
"Age": 35,
"Hobbies": [
"Arts",
"Sculpture"
]
},
{
"Id": "a5",
"FirstName": "Amanda",
"LastName": "Jake",
"Age": 27,
"Hobbies": [
"Music",
"Literature"
]
}
]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store