Description
Create a serverless REST API using AWS Lambda, API Gateway, and DynamoDB with CI/CD pipeline.
Objective
Deliver a scalable, serverless API with automated deployment and monitoring.
Solution
Environment Setup
- 1Install AWS CLI and configure credentials.
- 2Install Terraform or AWS SAM/Serverless Framework.
- 3Initialize Git repository for version control.
Define DynamoDB Table
- 1Create DynamoDB table with primary key (userId).
- 2Enable auto-scaling for read/write capacity.
- 3
terraform
resource "aws_dynamodb_table" "users" { name = "Users" billing_mode = "PAY_PER_REQUEST" hash_key = "userId" attribute { name = "userId" type = "S" } }
Create Lambda Functions
- 1Write Lambda functions for CRUD operations.
- 2Package functions with dependencies.
- 3
python
import boto3 import json dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('Users') def lambda_handler(event, context): if event['httpMethod'] == 'POST': body = json.loads(event['body']) table.put_item(Item={'userId': body['userId'], 'name': body['name']}) return {"statusCode": 200, "body": "User created"} elif event['httpMethod'] == 'GET': userId = event['queryStringParameters']['userId'] response = table.get_item(Key={'userId': userId}) return {"statusCode": 200, "body": json.dumps(response['Item'])}
Configure API Gateway
- 1Create REST API in API Gateway.
- 2Define resources (/users) and methods (GET, POST, PUT, DELETE).
- 3Integrate methods with Lambda functions.
- 4
terraform
resource "aws_api_gateway_rest_api" "api" { name = "users-api" description = "Serverless REST API" } resource "aws_api_gateway_resource" "users" { rest_api_id = aws_api_gateway_rest_api.api.id parent_id = aws_api_gateway_rest_api.api.root_resource_id path_part = "users" } resource "aws_api_gateway_method" "get_user" { rest_api_id = aws_api_gateway_rest_api.api.id resource_id = aws_api_gateway_resource.users.id http_method = "GET" authorization = "NONE" }
CI/CD Pipeline
- 1Set up AWS CodePipeline with CodeBuild.
- 2Source stage from GitHub/CodeCommit.
- 3Build stage runs tests and packages Lambda.
- 4Deploy stage applies changes to AWS.
- 5
yaml
version: 0.2 phases: install: commands: - pip install -r requirements.txt build: commands: - pytest - sam package --template-file template.yaml --s3-bucket mybucket --output-template-file packaged.yaml - sam deploy --template-file packaged.yaml --stack-name users-api --capabilities CAPABILITY_IAM
Deployment & Validation
- 1Deploy infrastructure with Terraform or SAM.
- 2Test API endpoints using Postman or curl.
- 3Monitor logs in CloudWatch.
- 4Validate CI/CD pipeline triggers on commits.
Tool Stack Used
- βοΈAWS Lambda
- π§API Gateway
- π§DynamoDB
- ποΈTerraform/SAM
- βοΈAWS CodePipeline
- βοΈAWS CodeBuild
- βοΈCloudWatch