Building a Serverless REST API on AWS in Python

Aloha!

Aashray
5 min readDec 6, 2020

So it’s Sunday evening and I’ve been wondering what to do. After not a lot of thinking, I decided to FINALLY build a Serverless REST API on AWS.

So here we go…

We’ll be using:

  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.

First thing’s first, let’s start by creating our DynamoDB Table which we’ll use to Store/Delete/Read, from our API.

Now that we have our DynamoDB Table ready, let’s work on writing our POST Lambda Function.

A quick catch here would be, we would need to assign an IAM Role to our Lambda function which has permission to access DynamoDB tables. Let’s see how we can do that below.

  1. Select Permissions inside the Lambda function you’ve just created.
  2. Select the Role Name which was created by AWS for you.

3. This will redirect you to the IAM page where we need to attach the policy we want.

4. For the sake of quickly finishing this tutorial, let’s just select DynamoDBFullAccess for now.

So far so good.

Let’s quickly write our code to finish our POST Operation from our Lambda.

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')
}

Let’s quickly test our lambda with the following input.

{
"Id": "a1",
"FirstName": "Robert",
"LastName": "Downy",
"Age": 45,
"Hobbies": [
"Movies",
"Books"
]
}

Looks like everything is working fine. Phew!

Let’s move on to the final piece of the puzzle, linking this Lambda function to an API Gateway.

We’ll be working with “REST API Private” for our use-case.

Once you are finished with all the naming/description formalities, click on “Actions” and Create a POST Method. After that add your function name and Save the API Gateway-Lambda integration.

Post this, use the following payload for smoke testing.

{
"Id": "a2",
"FirstName": "Jack",
"LastName": "King",
"Age": 30,
"Hobbies": [
"Sports",
"Arts"
]
}

You should be able to see this record in DynamoDB table now!

Now let’s quickly follow the same steps and create GET, DELETE functions and get back to enjoying movies on Netflix.

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')
}

NOTE: Since while creating our DynamoDB table, we defined both hash key and sort key, we need to add them both in our DELETE Function and DELETE Request!!!

Use the following JSON to test your DELETE Method.

{
"Id": "a2",
"FirstName": "Jack"
}

Eureka!

We have done it!

We have successfully built a Serverless REST API on AWS in Python!!

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"
]
}
]

2. Try to create different IAM Roles, to provide limited access to each Lambda Function.

Github Link: https://github.com/aashray18521/REST_Python_AWS_Lambda

Hope you enjoyed this tutorial!

Show your support by clapping!!!

Feel free to share your suggestions in the comments below!

Buy me a Coffee: https://www.buymeacoffee.com/aashray

Github: https://github.com/aashray18521

LinkedIn: https://www.linkedin.com/in/aashray-jain/

Twitter: https://twitter.com/aashray18521

--

--