Serverless API with Lambda

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

  1. 1Install AWS CLI and configure credentials.
  2. 2Install Terraform or AWS SAM/Serverless Framework.
  3. 3Initialize Git repository for version control.

Define DynamoDB Table

  1. 1Create DynamoDB table with primary key (userId).
  2. 2Enable auto-scaling for read/write capacity.
  3. 3
    terraformresource "aws_dynamodb_table" "users" {
      name           = "Users"
      billing_mode   = "PAY_PER_REQUEST"
      hash_key       = "userId"
    
      attribute {
        name = "userId"
        type = "S"
      }
    }

Create Lambda Functions

  1. 1Write Lambda functions for CRUD operations.
  2. 2Package functions with dependencies.
  3. 3
    pythonimport 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

  1. 1Create REST API in API Gateway.
  2. 2Define resources (/users) and methods (GET, POST, PUT, DELETE).
  3. 3Integrate methods with Lambda functions.
  4. 4
    terraformresource "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

  1. 1Set up AWS CodePipeline with CodeBuild.
  2. 2Source stage from GitHub/CodeCommit.
  3. 3Build stage runs tests and packages Lambda.
  4. 4Deploy stage applies changes to AWS.
  5. 5
    yamlversion: 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

  1. 1Deploy infrastructure with Terraform or SAM.
  2. 2Test API endpoints using Postman or curl.
  3. 3Monitor logs in CloudWatch.
  4. 4Validate CI/CD pipeline triggers on commits.

Tool Stack Used

  • ☁️AWS Lambda
  • πŸ”§API Gateway
  • πŸ”§DynamoDB
  • πŸ—οΈTerraform/SAM
  • ☁️AWS CodePipeline
  • ☁️AWS CodeBuild
  • ☁️CloudWatch