Serverless Web Application using S3, DynamoDB, API Gateway and AWS Lambda

Shreya Katuwal
7 min readDec 10, 2019

--

A starter’s guide to serverless on AWS.

We are going to create a Serverless Web Application utilizing:

  1. S3 to host the website
  2. AWS Lambda for serverless backend processing
  3. REST API using API Gateway
  4. DynamoDB to store data

Step 1: Create an s3 bucket:

To create a serverless application on AWS, you can begin by creating an S3 bucket for your website files.

Go to the AWS console Simple Storage Service (S3). First create a bucket, it can be named anything,(if it is going to be connected to a domain name then name it the same name as your domain eg. www.mydomainname.com). Bucket names must be unique throughout AWS. Other settings can be kept default while creating the bucket.

Now, to allow the website that is hosted from the bucket to be accessible by the public, bucket permissions must be modified and made public.

Open the bucket and go to the “Permissions” tab. Uncheck “Block all public access”.

Then go to “Bucket Policy” under the same tab and add the policy below, GetObject, which allows objects to be retrieved from the S3 bucket.

{
"Version": "2012-10-17",
"Id": "Policy1573139724816",
"Statement": [
{
"Sid": "Stmt1573139723269",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3::: your bucket name /*"
}
]
}

Next, go to the “Properties” tab, and select “Static Website Hosting”.

Select “Use this bucket to host a website”

In Index document, enter the name of the file which is going to be the default page.

(Optional) In the error document, enter an error page to redirect to, in case the index document is not found.

The endpoint link is the link you can use to access the website once it has been hosted.

Now, before uploading the files of our static website into this S3 bucket, we will complete a few other steps.

Step 2: Create an IAM Role for Lambda Function

Create an IAM role to assign to the Lambda function in the next step. This role is required to allow the Lambda function to have access to other AWS resources that are going to be used.

To allow the Lambda function write to Cloudwatch Logs via. the role, attach the LambdaBasicExecution permission policy.

Then, give the role a name and select Create Role.

After the role has been created, open the IAM Role and attach and inline policy.

Inline policies are policies that you can create and manage and embed directly into a single user, group, or role.

Here, we are going to create an inline policy to allow the role to have access to write to DynamoDB tables.

Choose DynamoDB as the service. In the actions that we want this role to be able to perform in DynamoDB, select PutItem. This will allow data to be entered into DynamoDB tables. In this example, data entered into the website hosted in s3 will be enabled to be entered into the DB tables, through the Lambda Function that this role will be attached to.

After Actions have been selected, in Resources you can select All Resources, which will allow the role to write to any DynamoDB created in your account.

If you select Specific Resource, then an arn (Amazon Resource Name) of a specific DynamoDB table will have to be attached so that the role will only be able to PutItems into that table. This is not necessary for now, so we will just stick to All Resources.

Once these steps have been completed, the role you need will be ready. Now it’s time to create the Lambda Function that will use this role.

Step 3: Create a DynamoDB Table

Create a DynamoDB Table, with a table name and partition key, which will behave as the primary key of the table.

In the table settings, use default settings and Create Table.

Here, we are creating a table to store user information, so the table is named UserTable and partition key is email.

After the table has been created, go to the Items tab and choose Create Item. Add fields that you require in your database as the items. When creating the item, select whether the field will contain Numbers, String, Boolean, etc.

In this example, we have items email(partition key), username, password, and user detail.

Step 4: Create a Lambda Function

Go to Lambda Management Console and select Create Function.

Choose Author from scratch, to add your own code and configurations to the function.

Give the Lambda function a name and choose a runtime, which the language that you are going use in your lambda function. In the execution role, select the IAM role that you just created, here it is dynamodb_write_role, to give the dynamoDB acess permissions to this lambda function. Then, select Create Function.

Now, add code into the Lambda Function, which will send data into the DynamoDB table when executed.

Since we are have created a function that uses Python as the runtime language, we must first import Boto3, which is the AWS Software Development Kit (SDK) for Python.

From the boto3 docs, we can find syntax for various AWS operations. Here we have added syntax for the PutItem operation in a DynamoDB table, by reference from the boto3 docs.

import boto3

dynamodb = boto3.client('dynamodb')

def lambda_handler(event, context):
username = event['username']
email = event['email']
password = event['password']
userdetails = event['userdetails']
dynamodb.put_item(TableName='UserData', Item={'username':{'S':username},'email':{'S':email},'password':{'S':password},'userdetails':{'S':userdetails}})
print(email)

This code inserts data(username, email, password and user details) into the table “User Data”.

Save the Lambda Function and to check if it works, click on Test. Create a new test function:

{
"username": "Sammy",
"email": "sammy@gmail.com
"password": "password123",
"userdetails": "Student at College of Nepal."
}

and test it. If it works, then you will see the items added to your DynamoDB table.

Step 5: Create an API Gateway

An API Gateway is needed to integrate the static website in the S3 bucket with the Lambda function.

Create a new REST API, and give it a name. Once the API has been created, it must be configured.

From the Actions menu, create a Resource. Enable API Gateway CORS. A method OPTIONS with integration type Mock will automatically be created when you allow CORS. Mock returns a response using API Gateway Mappings.

Then, create another POST Method. Choose Lambda Function as the integration type and select the Lambda function that was just created. This will add the API Gateway we are creating as a trigger to the Lambda Function created in the previous step, and the POST method will enable data to be submitted to the function.

The POST method execution will look like this:

Now, to test if the API gateway has been correctly integrated with your Lambda function, click on TEST. You can use the same test function you used for your Lambda Function above. If it works, the value returned will be Null and your DynamoDB table will be updated.

Deploy the API:

Now, under Actions, select Deploy API.

Create a deployment stage with a stage name and select deploy. You will be provided with an Invoke URL. Copy the URL for the next step.

Step 6: Connect your Website with API Gateway

To connect your website with API Gateway, create a variable in the JavaScript file of your static website and assign to it the InvokeURL from the previous step.

eg:

var api = "https://j6ngwm8og5.execute-api.us-east-1.amazonaws.com/DEV/user"

Now that our setup has been completed, the final step is to add the static website files into your S3 bucket.

Step 7: Upload the Static Website into S3

Select the website files to upload to your s3 bucket (including the .js file that we just added the invokeURL in).

Click on next and manage the public permissions. Set Read permissions to Everyone, then click Upload.

Now your website has been deployed!

To open it, go to bucket properties -> Static Web Hosting (which we enabled in Step 1), and click on the Endpoint URL.

From there, you will be able to access your website from the browser.

To test if the entire configuration worked, enter data into your form and check to see if your DynamoDB table has been updated.

For this example, we created a simple form with four fields.

Make sure the field ids in your website are the same as the items you added in your DynamoDB table.

Simple front-end of our site

If your table got updated once you submitted the form, then all the steps have been completed successfully!

--

--