Serverless Microservice CRUD & Load test hands-on
LevelUp! Lab for Serverless
Project Summary: Building a Serverless API with AWS
This project provides a comprehensive guide to creating a serverless API using Amazon Web Services (AWS). The high-level design involves utilizing Amazon API Gateway, AWS Lambda functions, and DynamoDB for data storage.
This project serves as a comprehensive tutorial for building and deploying serverless APIs on AWS, utilizing key services such as API Gateway, Lambda, and DynamoDB, while also introducing concepts like AWS SAM for further exploration.
Lab Overview And High Level Design
Let's start with the High Level Design. An Amazon API Gateway is a collection of resources and methods. For this tutorial, you create one resource (DynamoDBManager) and define one method (POST) on it. The method is backed by a Lambda function (LambdaFunctionOverHttps). That is, when you call the API through an HTTPS endpoint, Amazon API Gateway invokes the Lambda function.
The POST method on the DynamoDBManager resource supports the following DynamoDB operations:
The request payload you send in the POST request identifies the DynamoDB operation and provides necessary data. For example:
The following is a sample request payload for a DynamoDB create item operation:
{
"operation": "create",
"tableName": "lambda-apigateway",
"payload": {
"Item": {
"id": "1",
"name": "Bob"
}
}
}
The following is a sample request payload for a DynamoDB read item operation:
{
"operation": "read",
"tableName": "lambda-apigateway",
"payload": {
"Key": {
"id": "1"
}
}
}
Setup
Create Lambda IAM Role
Create the execution role that gives your function permission to access AWS resources.
To create an execution role
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"Stmt1428341300017",
"Action":[
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:UpdateItem"
],
"Effect":"Allow",
"Resource":"*"
},
{
"Sid":"",
"Resource":"*",
"Action":[
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect":"Allow"
}
]
}
Create Lambda Function
To create the function
Example Python Code
from __future__ import print_function
import boto3
import json
print('Loading function')
def lambda_handler(event, context):
'''Provide an event that contains the following keys:
- operation: one of the operations in the operations dict below
- tableName: required for operations that interact with DynamoDB
- payload: a parameter to pass to the operation being performed
'''
#print("Received event: " + json.dumps(event, indent=2))
operation = event['operation']
if 'tableName' in event:
dynamo = boto3.resource('dynamodb').Table(event['tableName'])
operations = {
'create': lambda x: dynamo.put_item(**x),
'read': lambda x: dynamo.get_item(**x),
'update': lambda x: dynamo.update_item(**x),
'delete': lambda x: dynamo.delete_item(**x),
'list': lambda x: dynamo.scan(**x),
'echo': lambda x: x,
'ping': lambda x: 'pong'
}
if operation in operations:
return operations[operation](event.get('payload'))
else:
raise ValueError('Unrecognized operation "{}"'.format(operation))
Test Lambda Function
Let's test our newly created function. We haven't created DynamoDB and the API yet, so we'll do a sample echo operation. The function should output whatever input we pass.
{
"operation": "echo",
"payload": {
"somekey1": "somevalue1",
"somekey2": "somevalue2"
}
}
We're all set to create DynamoDB table and an API using our lambda as backend!
Create DynamoDB Table
Create the DynamoDB table that the Lambda function uses.
To create a DynamoDB table
Create API
To create the API
领英推荐
Deploy the API
In this step, you deploy the API that you created to a stage called prod.
Running our solution
{
"operation": "create",
"tableName": "lambda-apigateway",
"payload": {
"Item": {
"id": "1234ABCD",
"number": 5
}
}
}
$ curl -X POST -d "{\"operation\":\"create\",\"tableName\":\"lambda-apigateway\",\"payload\":{\"Item\":{\"id\":\"1\",\"name\":\"Bob\"}}}" https://$API.execute-api.$REGION.amazonaws.com/prod/DynamoDBManager
{
"operation": "list",
"tableName": "lambda-apigateway",
"payload": {
}
}
We have successfully created a serverless API using API Gateway, Lambda, and DynamoDB!
Performance test using Postman
Infrastructure deployment:
The AWS Serverless Application Model (AWS SAM) is a toolkit that improves the developer experience of building and running serverless applications on AWS.
AWS SAM template specification – An open-source framework that you can use to define your serverless application infrastructure on AWS.
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: SAM template for API Gateway, Lambda, and DynamoDB CRUD project architecture
Resources:
DynamoDBTable:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: lambda-apigateway
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
LambdaFunction:
Type: 'AWS::Serverless::Function'
Properties:
Handler: lambda_function.lambda_handler
Runtime: python3.8
Policies:
- DynamoDBCrudPolicy: {}
Environment:
Variables:
TABLE_NAME: !Ref DynamoDBTable
Events:
ApiGatewayEvent:
Type: Api
Properties:
Path: /dynamodbmanager
Method: post
Outputs:
ApiUrl:
Description: URL of the API Gateway endpoint
Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/dynamodbmanager'
DynamoDBTableName:
Description: Name of the DynamoDB table
Value: !Ref DynamoDBTable
Cleanup
Let's clean up the resources we have created for this lab.
Cleaning up DynamoDB
Cloud Support Engineer | System Admin | Marine in Tech | Crafting On-Premise to Cloud Solutions"
1 年Thanks for posting
Cloud Solution Architect | System Design | AWS CSA | DevOps | Kubernetes | Terraform. Talks about #AWS, #Cloud, #SystemDesign, #Kubernetes, #Terraform, #Modernization
1 年Excellent! Thank for sharing serverless micro service hands-on.