Skip to content

SPRAVEEN1221/Springboot-aws-lambda

Repository files navigation

Spring Boot + AWS Lambda Integration Demo

A simple Spring Boot application that demonstrates how to invoke AWS Lambda functions and fetch data from them.

πŸ“‹ Table of Contents


🎯 Project Overview

This project demonstrates:

  1. βœ… Installing and configuring AWS CLI locally
  2. βœ… Creating AWS Lambda functions
  3. βœ… Spring Boot application invoking Lambda functions
  4. βœ… Fetching data from Lambda using Spring Boot
  5. βœ… RESTful API endpoints to interact with Lambda

πŸ“¦ Prerequisites

  • Java 17 or higher
  • Maven 3.6+
  • AWS Account (free tier is sufficient)
  • Internet connection for AWS API calls

πŸ”§ AWS CLI Installation

Windows Installation

Option 1: Using MSI Installer (Recommended)

  1. Download AWS CLI MSI installer:

    https://awscli.amazonaws.com/AWSCLIV2.msi
    
  2. Run the downloaded MSI installer

  3. Follow the installation wizard

  4. Verify installation:

    aws --version

    Should output: aws-cli/2.x.x Python/3.x.x Windows/...

Option 2: Using Command Line

msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

macOS Installation

Using Homebrew:

brew install awscli

Using Package:

curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /

Linux Installation

Ubuntu/Debian:

sudo apt update
sudo apt install awscli

Using Python pip:

pip install awscli --upgrade --user

Using Binary:

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

Verify Installation

aws --version

πŸ” AWS Configuration

Step 1: Get AWS Credentials

  1. Log in to AWS Console
  2. Go to IAM (Identity and Access Management)
  3. Click Users β†’ Add User
  4. Create user with Programmatic access
  5. Attach policy: AWSLambdaFullAccess
  6. Save your:
    • Access Key ID
    • Secret Access Key

Step 2: Configure AWS CLI

aws configure

Enter your credentials:

AWS Access Key ID: YOUR_ACCESS_KEY_ID
AWS Secret Access Key: YOUR_SECRET_ACCESS_KEY
Default region name: us-east-1
Default output format: json

Step 3: Verify Configuration

aws sts get-caller-identity

This should show your AWS account details.

Alternative: Using Credentials File

Create file at:

  • Windows: C:\Users\USERNAME\.aws\credentials
  • Mac/Linux: ~/.aws/credentials
[default]
aws_access_key_id = YOUR_ACCESS_KEY_ID
aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

Create config file at:

  • Windows: C:\Users\USERNAME\.aws\config
  • Mac/Linux: ~/.aws/config
[default]
region = us-east-1
output = json

πŸš€ Lambda Function Setup

Option 1: Using AWS Console

  1. Go to AWS Lambda Console:

    https://console.aws.amazon.com/lambda
    
  2. Create Function 1: Simple Hello

    • Click "Create function"
    • Choose "Author from scratch"
    • Function name: helloWorldFunction
    • Runtime: Python 3.9
    • Click "Create function"
  3. Add Code:

    import json
    
    def lambda_handler(event, context):
        name = event.get('name', 'Guest')
        
        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': f'Hello {name} from AWS Lambda!',
                'timestamp': context.request_id
            })
        }
  4. Create Function 2: Get User Data

    • Function name: getUserDataFunction
    • Runtime: Python 3.9
    • Code:
    import json
    from datetime import datetime
    
    def lambda_handler(event, context):
        name = event.get('name', 'Unknown')
        email = event.get('email', 'no-email@example.com')
        
        response = {
            'message': 'User data processed successfully by Lambda!',
            'userName': name,
            'userEmail': email,
            'timestamp': datetime.now().isoformat()
        }
        
        return response
  5. Deploy both functions

Option 2: Using AWS CLI

Create Python Lambda function:

# Create lambda_function.py first, then:
zip function.zip lambda_function.py

aws lambda create-function \
    --function-name getUserDataFunction \
    --runtime python3.9 \
    --role arn:aws:iam::YOUR_ACCOUNT_ID:role/lambda-execution-role \
    --handler lambda_function.lambda_handler \
    --zip-file fileb://function.zip

🌱 Spring Boot Setup

Step 1: Clone or Navigate to Project

cd "D:\Spring Boot\sprinBoot-lambda-demo"

Step 2: Update Lambda Function Names

In LambdaService.java, update function names if needed:

.functionName("getUserDataFunction")  // Your actual Lambda function name

Step 3: Build Project

mvn clean install

▢️ Running the Application

Start Spring Boot Application

mvn spring-boot:run

Or run the JAR:

java -jar target/sprinBoot-lambda-demo-0.0.1-SNAPSHOT.jar

The application will start on: http://localhost:8080


πŸ“‘ API Endpoints

1. Health Check

GET http://localhost:8080/api/lambda/health

Response:

Spring Boot Lambda Integration is running!

2. Simple Lambda Invocation

GET http://localhost:8080/api/lambda/hello?name=John

Response:

{
  "message": "Hello John from AWS Lambda!",
  "timestamp": "abc-123-xyz"
}

3. Invoke Lambda with POST Request

POST http://localhost:8080/api/lambda/invoke
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com"
}

Response:

{
  "message": "User data processed successfully by Lambda!",
  "userName": "John Doe",
  "userEmail": "john@example.com",
  "timestamp": "2025-10-27T10:30:00.000Z"
}

4. Get User Data via Query Parameters

GET http://localhost:8080/api/lambda/user?name=Jane&email=jane@example.com

Response:

{
  "message": "User data processed successfully by Lambda!",
  "userName": "Jane",
  "userEmail": "jane@example.com",
  "timestamp": "2025-10-27T10:30:00.000Z"
}

πŸ§ͺ Testing

Using cURL

Test Health:

curl http://localhost:8080/api/lambda/health

Test Simple Lambda:

curl "http://localhost:8080/api/lambda/hello?name=Alice"

Test POST Request:

curl -X POST http://localhost:8080/api/lambda/invoke \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob","email":"bob@example.com"}'

Using Postman

  1. Import collection or create new requests
  2. Set base URL: http://localhost:8080
  3. Test each endpoint above

Using Browser

Open: http://localhost:8080/api/lambda/health


πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client        β”‚
β”‚  (Browser/API)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ HTTP Request
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Spring Boot    β”‚
β”‚  Application    β”‚
β”‚  (Port 8080)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ AWS SDK
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   AWS Lambda    β”‚
β”‚   Functions     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Flow Explanation:

  1. Client sends HTTP request to Spring Boot
  2. Spring Boot Controller receives request
  3. Lambda Service invokes AWS Lambda using AWS SDK
  4. AWS Lambda processes the request
  5. Lambda returns response to Spring Boot
  6. Spring Boot sends response back to client

πŸ“‚ Project Structure

sprinBoot-lambda-demo/
β”‚
β”œβ”€β”€ src/main/java/com/example/springbootlambdademo/
β”‚   β”œβ”€β”€ SprinBootLambdaDemoApplication.java   # Main class
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── AwsConfig.java                    # AWS configuration
β”‚   β”œβ”€β”€ controller/
β”‚   β”‚   └── LambdaController.java             # REST endpoints
β”‚   β”œβ”€β”€ service/
β”‚   β”‚   └── LambdaService.java                # Lambda invocation logic
β”‚   └── model/
β”‚       β”œβ”€β”€ UserRequest.java                   # Request model
β”‚       └── UserResponse.java                  # Response model
β”‚
β”œβ”€β”€ src/main/resources/
β”‚   └── application.properties                 # App configuration
β”‚
β”œβ”€β”€ pom.xml                                    # Maven dependencies
└── lambda-functions.md                        # Lambda code samples

πŸ” Key Components Explained

1. AwsConfig.java

  • Configures AWS Lambda client
  • Sets AWS region
  • Uses default credentials provider (reads from ~/.aws/credentials)

2. LambdaService.java

  • Contains business logic to invoke Lambda
  • Converts Java objects to JSON
  • Sends payload to Lambda
  • Receives and parses Lambda response

3. LambdaController.java

  • Exposes REST API endpoints
  • Handles HTTP requests/responses
  • Calls LambdaService methods

4. Models (UserRequest/UserResponse)

  • POJOs for request/response data
  • Jackson serialization/deserialization

πŸ› οΈ Troubleshooting

Issue 1: AWS Credentials Not Found

Error: Unable to load credentials

Solution:

aws configure

Or check: ~/.aws/credentials file exists

Issue 2: Lambda Function Not Found

Error: ResourceNotFoundException

Solution:

  • Verify function name in LambdaService.java
  • Check function exists in AWS Console
  • Ensure correct AWS region

Issue 3: Access Denied

Error: AccessDeniedException

Solution:

  • Check IAM user has AWSLambdaFullAccess permission
  • Verify AWS credentials are correct

Issue 4: Connection Timeout

Solution:

  • Check internet connection
  • Verify AWS region is correct
  • Check firewall settings

πŸ“š Additional Resources


πŸ“ Notes

  • This is a demo project for learning purposes
  • Use IAM roles with minimal permissions in production
  • Consider using AWS Secrets Manager for credentials in production
  • Lambda cold start times may affect response time

🀝 Contributing

Feel free to improve this demo by:

  • Adding error handling
  • Implementing retry logic
  • Adding unit tests
  • Improving documentation

πŸ“„ License

This project is for educational purposes.


Made with ❀️ for learning Spring Boot + AWS Lambda Integration

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages