
How to build a simple serverless application
This post will help you know how to build a simple serverless application.
AdministratorAccess
permission.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]
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
sam build
to build the project1
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
.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 namedlambda_handler
, which will be called when receiving a request.events
: This folder only contains a file nameevent.json
, which can help build a request forlambda_handler
, you can update the parameters if needstests
: Running the test case forlambda_handler
helps to check the logic right or not.
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
http://127.0.0.1:3000/chat
to check if this project works well. 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
- We have to understand a few commands, including
sam init
,sam build
,sam local start-api
, andsam deply
. We just need to developlambda_handler
to handle our business logic inapp.py
file. - We can easily manage and monitor our resources using
AWS CloudFormation
andAWS CloudWatch
- You can see the source code in GitHub.