top of page

Tutorial to build a serverless web application

Updated: Nov 1, 2023

Tutorial to build a serverless web application


Tutorial Objectives:

  • Learn to build a serverless web application using Lambda, API Gateway, DynamoDB, Cognito and Amplify.


Step 1: Host a Static Website

1. Log on to your AWS Management Console and Select a Region: N. Virginia.

  • Search for AWS CodeCommit and open the console

  • Click on Create Repository

  • Repository Name: wildrydes-site and create Repository and copy the URL.



2. Open your AWS management console in another new tab and navigate to Cloud9.Create environment

Name: MyCloud9env, click on Next Step->Next Step->Create environment.

  • Download wildrydes-site.zip from here into your local machine.

  • Once the environment is up and running, Click on the File->Upload local files…


And select the downloaded wildrydes-site.zip folder and click upload.

  • Now run the previously copied git clone command in the cloud9 terminal.

  • Run the following command to unzip the wildrydes-site.zip file.

unzip wildrydes-site.zip -d wildrydes-site

  • When prompted enter A and click enter

  • Once the process is finished, click on the wildrydes-site folder and check the folder.

Now, Run the following command

cd wildrydes-site/
git add .
git commit -m "initial commit"
git push

3. In the new tab open AWS Amplify console, under Deliver click on Get Started.

  • Select AWS CodeCommit and click Continue.

  • Select repo from the dropdown and click Next. Keep branch as master and Next.

  • Enable Allow AWS Amplify to automatically deploy all files hosted in your project root directory and Next->Save and Deploy.

It will take a couple of minutes for Amplify Console to create the necessary resources and to deploy your code.

  • Once completed, click on the site image to launch your Wild Rydes site.


Step 2:In the new tab, Open Amazon Simple Email Service (SES) console.

In the left panel under Configuration, select Verified identities.

Click on Create Identity.

Under Create Identity, choose Email Address, give your email-id.

Scroll down and click on Create identity.

You will then receive a email for verification, verify your email with the provided link.

After verification, you can see the identity status changes to Verified.

Now, Create an Amazon CognitoUser Pool
1. In the new tab, Open Amazon Cognito console
  • Choose Create a User Pool

  • In Authentication providers, scroll down and check Username and click on Next.

  • In Password policy, scroll down to Multi-factor authentication and choose NO MFA and scroll down and click on Next.

  • Keep the Configure sign-up experience default and scroll down and click Next.

  • In Configure Message Delivery, in From Email Address choose your email-id from the dropdown menu, scroll down and click on Next.

  • User pool name: WildRydes.

Scroll down and give App Client Name : WildRydesWebApp

  • Uncheck the Generate clientsecret option and click on Next.

  • Review and create click on Create User Pool.

You can see your User Pool is created.

To copy User Pool ID, see the below image.

To copy ClientId click on WildRydes, go to App Integration, scroll down to last and copy the ClientId for further use.

In the Cloud9 console, open the open ‘wild-ryde-site/js/config.js’

  • Update the cognito section with the correct values for the region, user pool id, userpoolClientId, you just created and click control+s.

Updated config.jsfile should look like this:

  • Save the modified file and push it to repository to have it automatically deploy to Amplify Console

git add .
git commit -m "Updated config.js"
git push

Visit /register.html under your website domain, or choose the Giddy Up! button on the homepage of your site.


  • Complete the registration form by entering Email, Password and confirm the password and click to Lets Ryde!

  • Verify email by entering code.

  • After successful verification Sign in using email and password you entered.

  • If successful you should be redirected to /ride.html. You should see a notification that the API is not configured.


Step 3: Serverless Service Backend

1. Create Amazon DynamoDB Table

  • Open Amazon DynamoDB Service in new tab

  • Choose Create table

  • Table Name: Rides

  • Enter RideId for the Partition key and select String for the key type.

  • Check the Use default settings box and choose Create.

  • Scroll to the bottom of the Overview section of new table and note the ARN. We will use this in the next section.

2. Create an IAM Role for Lambda function

  • Open Amazon IAM Service in new tab

  • Select Roles and create new role

  • Select Lambda for the role type from the AWS service group, then click Next: Permissions.

  • In the attach permission policy, search for AWSLambdaBasicExecutionRole and click the check box.


  • Choose Next Step.

  • Role Name: WildRydesLambda

  • Choose Create Role.

  • Type WildRydesLambda into the filter box on the Roles page and choose the role.

  • On the Permissions tab, choose the Add inline policy link to create a new inline policy.

  • Select Choose a service.

  • Type DynamoDB into the search box labeled Find a service and select DynamoDB.

  • Choose Select actions.

  • Type PutItem into the search box labeled Filter actions and check the box next to PutItem when it appears.

  • Select the Resources section.

  • With the Specific option selected, choose the Add ARN link in the table section.

  • Paste the ARN of the table you created in the previous section in the Specify ARN for table field, and choose Add.

  • Choose Review Policy.

  • Enter Policy name: DynamoDBWriteAccess and choose Create policy.

3. Create a Lambda Function for Handling Requests

  • Open AWS Lambda service in new tab

  • Choose Create Function

  • Keep the default Author from scratch card selected.

  • Enter RequestUnicorn in the Name field.

  • Select Node.js 14.x for the Runtime.

  • Choose use an existing role from the Role dropdown.

  • Select WildRydesLambda from the Existing Role dropdown.

  • Click on Create function.

  • Scroll down to the Function code section and replace the existing code in the index.js code editor with the code in the requestUnicorn.txt. Download requestUnicorn.txt file from here

  • Click "Save" in the upper right corner of the page.

  • Click to test, choose new event

  • Named it as TestRequestEvent

  • Copy and paste the following test event into the editor:

{
    "path": "/ride",
    "httpMethod": "POST",
    "headers": {
        "Accept": "*/*",
        "Authorization": "eyJraWQiOiJLTzRVMWZs",
        "content-type": "application/json; charset=UTF-8"
    },
    "queryStringParameters": null,
    "pathParameters": null,
    "requestContext": {
        "authorizer": {
            "claims": {
                "cognito:username": "the_username"
            }
        }
    },
    "body": "{\"PickupLocation\":{\"Latitude\":47.6174755835663,\"Longitude\":-122.28837066650185}}"
}
  • Save the changes and Test

  • You will get the Execution result as succeeded as below.

  • Deploy the code.


Step 4: Deploy a RESTful API

1. Create a new REST API

  • In the AWS Management Console, click Services then select API Gateway under Application Services.

  • Choose an API type as REST API Click on Build

  • Choose the Protocol: REST

  • Create New API: New API

  • API Name: WildRydes

  • Endpoint Type: Edge optimized

  • Click Create API

2. Create a Cognito User Pools Authorizer

  • Under your newly created API, choose Authorizers.

  • Choose Create New Authorizer

  • Authorizer name: WildRydes

  • Type: Cognito

  • Region: us-east-1

  • Enter WildRydes in the Cognito User Pool input.

  • Token Source: Authorization and click on create.


To Verify Authorizer configuration

  • Open a new browser tab and visit /ride.html

  • If you are redirected to the sign-in page, sign in with the user you created in the last module. You will be redirected back to /ride.html.

  • Copy the auth token from the notification on the /ride.html

  • Go back to API Gateway tab

  • Click Test at the bottom of the card for the authorizer.

  • Paste the auth token into the Authorization Token field in the popup dialog.

  • Click Test button and verify that the response code is 200.

3. Create a new resource and method

  • click on Resources under your WildRydes API.

  • From the Actions dropdown select Create Resource.

  • Resource Name: ride

  • Ensure the Resource Path is set to ride.

  • Select Enable API Gateway CORS for the resource.

  • Click Create Resource.

  • With the newly created /ride resource selected, from the Action dropdown select Create Method.

  • Select POST from the new dropdown, then click the checkmark.

  • Integration type: Lambda Function

  • Check the box for Use Lambda Proxy integration

  • Lambda Region: us-east-1

  • Lambda Function: RequestUnicorn

  • Click Save.

  • When prompted to give Amazon API Gateway permission to invoke your function, choose OK.

  • Choose on the Method Request card.

  • Choose the pencil icon next to Authorization.

  • Select the WildRydes Cognito user pool authorizer from the drop-down list, and click the checkmark icon.

4. Deploy API

  • In the Actions drop-down list select Deploy API.

  • Select [New Stage] in the Deployment stage drop-down list.

  • Enter Stage Name: prod

  • Choose Deploy.

  • Note the Invoke URL. You will use it in the next section.

5. Update the website config

  • Open the config.js file in a cloud9 editor.

  • Update the invokeUrl setting under the api key in the config.js file.

  • Save the changes by ctrl+s and run the following command

git add .
git commit -m “Updated config.js”
git push
  • Now Visit /ride.html under your website domain.

  • If you are redirected to the sign in page, sign in with the user you created in the previous module.

  • After the map has loaded, click anywhere on the map to set a pickup location.

  • Choose Request Unicorn. You should see a notification in the right sidebar that a unicorn is on its way and then see a unicorn icon.

Note: If you no longer need the resources, delete DynamoDB Table, API, Lambda Function, Role, User Pool, Repository, Cloud9 environment and wildrydes-site app (Amazon Amplify).


Build_a_Serverless_Web_application
.pdf
Download PDF • 1.75MB

Was this document helpful? How can we make this document better? Please provide your insights. You can download PDF version for reference.


We provide the best AWS training from Pune, India.

For aws certification contact us now.

844 views10 comments

10 Comments


Very easy to understand the concept  building a serverless web application

Like

Atchaya B
Atchaya B
Apr 09

Helpful to learn the concept of build a serverless web application

Like

Through this blog building a serverless web application was understood

Like

Gokulnath
Gokulnath
Apr 08

 building a serverless web application was understood


Like

The explanation of building a serverless web application was very clear and easy to follow.


Like
bottom of page