logo
Menu
How to build a simple serverless application

How to build a simple serverless application

This post will help you know how to build a simple serverless application.

Published Jan 1, 2024
If you are interested in serverless but you don't know how to use it in AWS, if you're a newer to serverless and eager to know how to develop a serverless application quickly. This article will help you out. There are five parts in this article as below:

Prerequisites

Creating an AWS account

Open the Amazon Web Services (AWS) home page. Choose Create an AWS Account. If you have an AWS account aready, please choose Sign in to the Console.

Configuring IAM

You cannot allow to access AWS services if you don't have AWS Identity and Access Management (IAM) permissions, you can create a user and setup up IAM AdministratorAccess permission.
Configuring IAM

Installing and Configuring AWS CLI

AWS Command Line Interface (CLI) is an open source tool that enables you to interact with AWS services using commands in your command-line shell. You can refer to AWS CLI to install it.

Setup credentials

It will be very easy to use AWS CLI to access AWS services if you setup AWS credentials.
Create access key
Choose the user you have created, and then create access key
Create access key
Setup AK/SK
1
2
3
4
5
$ aws configure
AWS Access Key ID [*******************]:
AWS Secret Access Key [*********************]:
Default region name [us-east-1]:
Default output format [json]

Installing SAM CLI

If you don’t have SAM CLI installed into your local machine, please follow this link Installing the AWS SAM CLI

Installing Python

If you want to use python as your application language, you have to install python in your local pc, you can follow this link Python.

Build

Init project

Using command sam init --name assistant --runtime python3.9 to create a project named assistant using Python3.9.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
$ sam init --name assistant --runtime python3.9
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
1 - Hello World Example
2 - Hello World Example with Powertools for AWS Lambda
3 - Infrastructure event management
4 - Multi-step workflow
5 - Lambda EFS example
6 - Serverless Connector Hello World Example
7 - Multi-step workflow with Connectors
Template: 1

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is pip.
We will proceed copying the template using pip.

Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: y
X-Ray will incur an additional cost. View https://aws.amazon.com/xray/pricing/ for more details

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: y
AppInsights monitoring may incur additional cost. View https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/appinsights-what-is.html#appinsights-pricing for more details

Would you like to set Structured Logging in JSON format on your Lambda functions? [y/N]: y
Structured Logging in JSON format might incur an additional cost. View https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html#monitoring-cloudwatchlogs-pricing for more details

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

-----------------------
Generating application:
-----------------------
Name: assistant
Runtime: python3.9
Architectures: x86_64
Dependency Manager: pip
Application Template: hello-world
Output Directory: .
Configuration file: assistant/samconfig.toml

Next steps can be found in the README file at assistant/README.md


Commands you can use next
=========================
[*] Create pipeline: cd assistant && sam pipeline init --bootstrap
[*] Validate SAM template: cd assistant && sam validate
[*] Test Function in the Cloud: cd assistant && sam sync --stack-name {stack-name} --watch

Build project

Using command sam build to build the project
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ sam build
Starting Build use cache
Manifest is not changed for (AssistantFunction), running incremental build
Building codeuri: /Users/*****/Documents/workspace/assistant/assistant runtime: python3.9 metadata: {} architecture: x86_64 functions: AssistantFunction
Running PythonPipBuilder:CopySource
Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts : .aws-sam/build
Built Template : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided

Project structure

Here is the structure of this project.
Project Structure
Here are the explanation for this project structure.
  • .aws-sam : SAM will store the temporary file in this folder when building, deplying etc.
  • assistant : This folder contains the core codes, app.py includes a Lambda function named lambda_handler, which will be called when receiving a request.
  • events : This folder only contains a file name event.json, which can help build a request for lambda_handler , you can update the parameters if needs
  • tests : Running the test case for lambda_handler helps to check the logic right or not.

Test

Running command sam local start-api to test locally.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ sam local start-api
Initializing the lambda functions containers.
Local image is up-to-date
Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.

Mounting /Users/****/Documents/workspace/assistant/.aws-sam/build/AssistantFunction as /var/task:ro,delegated, inside runtime container
Containers Initialization is done.
Mounting AssistantFunction at http://127.0.0.1:3000/chat [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be
reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You
only need to restart SAM CLI if you update your AWS SAM template
2024-01-01 16:48:48 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:3000
2024-01-01 16:48:48 Press CTRL+C to quit
You can visit http://127.0.0.1:3000/chat to check if this project works well.
Test your project locally

Deploy

Running command sam deploy to deploy this project in your AWS account.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
$ sam deploy

Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-****
A different default S3 bucket can be set in samconfig.toml
Or by specifying --s3-bucket explicitly.
Uploading to assistant-stack/7a797a9b5a47aad50fab9d646e9c15d7 533743 / 533743 (100.00%)

Deploying with following values
===============================
Stack name : assistant-stack
Region : us-east-1
Confirm changeset : True
Disable rollback : False
Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-****
Capabilities : ["CAPABILITY_IAM"]
Parameter overrides : {}
Signing Profiles : {}

Initiating deployment
=====================

Uploading to assistant-stack/7415aaffeac2ca8bd115d8ffc0421cc3.template 1824 / 1824 (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation LogicalResourceId ResourceType Replacement
-------------------------------------------------------------------------------------------------------------------------------------------------------------
* Modify AssistantFunction AWS::Lambda::Function False
* Modify ServerlessRestApi AWS::ApiGateway::RestApi False
-------------------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-east-1:157854716818:changeSet/samcli-deploy1704082336/0aa7d762-0a19-4696-b1cd-8ad8c5f19fcc

Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2024-01-01 12:12:42 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus ResourceType LogicalResourceId ResourceStatusReason
-------------------------------------------------------------------------------------------------------------------------------------------------------------
UPDATE_IN_PROGRESS AWS::CloudFormation::Stack assistant-stack User Initiated
UPDATE_IN_PROGRESS AWS::Lambda::Function AssistantFunction -
UPDATE_COMPLETE AWS::Lambda::Function AssistantFunction -
UPDATE_COMPLETE_CLEANUP_IN_PROGRESS AWS::CloudFormation::Stack assistant-stack -
UPDATE_COMPLETE AWS::CloudFormation::Stack assistant-stack -
-------------------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Key AssistantApi
Description API Gateway endpoint URL for Prod stage for Assistant function
Value https://****.execute-api.us-east-1.amazonaws.com/Prod/chat/

Key AssistantFunction
Description Assistant Lambda Function ARN
Value arn:aws:lambda:us-east-1:157854716818:function:assistant-stack-AssistantFunction-XkeA4K9pFIIj

Key AssistantFunctionIamRole
Description Implicit IAM Role created for Assistant function
Value arn:aws:iam::157854716818:role/assistant-stack-AssistantFunctionRole-SmM7smgetiNb
---------------------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - assistant-stack in us-east-1
And then, you can visit AssistantApi's value to check if this project works well.
Deploy your project and then check it
Here are the resources about this project.
Resources of this prject in CloudFormation
Here is the resource in Lambda
Resource in Lambda
Here is the monitor for this project.
Monitor for Lambda

Conclusion

AWS SAM is really a sample tool to help us develop serverless application.
  • We have to understand a few commands, including sam init, sam build, sam local start-api , and sam deply. We just need to develop lambda_handler to handle our business logic in app.py file.
  • We can easily manage and monitor our resources using AWS CloudFormation and AWS CloudWatch
  • You can see the source code in GitHub.

Comments