Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created December 26, 2024 22:31
Show Gist options
  • Save decagondev/28c027699f1bf9a5c7165cf3f52745af to your computer and use it in GitHub Desktop.
Save decagondev/28c027699f1bf9a5c7165cf3f52745af to your computer and use it in GitHub Desktop.

Hello World AWS Lambda Function with Gradle

This guide walks you through creating a simple Hello World AWS Lambda function using Java and Gradle, ready for deployment using our automated deployment script.

Project Setup

  1. Create a new directory for your project:
mkdir hello-world-lambda
cd hello-world-lambda
  1. Initialize a new Gradle project:
gradle init --type java-application

When prompted:

  • Choose 2 for application
  • Choose 3 for Java
  • Choose 1 for Groovy
  • Project name: hello-world-lambda
  • Source package: com.example.lambda

Configure Gradle

Replace the contents of build.gradle with:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation platform('com.amazonaws:aws-java-sdk-bom:1.12.261')
    implementation 'com.amazonaws:aws-lambda-java-core:1.2.2'
    implementation 'com.amazonaws:aws-lambda-java-events:3.11.0'
    implementation 'com.google.code.gson:gson:2.10.1'
    
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
}

java {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

test {
    useJUnitPlatform()
}

jar {
    manifest {
        attributes 'Main-Class': 'com.example.lambda.Handler'
    }
    
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
    
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

Create Lambda Handler

  1. Create the handler class in src/main/java/com/example/lambda/Handler.java:
package com.example.lambda;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.google.gson.Gson;
import java.util.Map;
import java.util.HashMap;

public class Handler implements RequestHandler<Map<String, Object>, Map<String, Object>> {
    private final Gson gson = new Gson();

    @Override
    public Map<String, Object> handleRequest(Map<String, Object> input, Context context) {
        context.getLogger().log("Input: " + gson.toJson(input));
        
        Map<String, Object> response = new HashMap<>();
        response.put("statusCode", 200);
        response.put("body", "Hello from AWS Lambda!");
        
        return response;
    }
}

Project Structure

Your project should now look like this:

hello-world-lambda/
├── build.gradle
├── gradlew
├── gradlew.bat
└── src/
    └── main/
        └── java/
            └── com/
                └── example/
                    └── lambda/
                        └── Handler.java

Build and Deploy

  1. Build the project:
./gradlew clean build
  1. Run the deployment script:
python deploy_lambda.py

When prompted, provide the following information:

  • Project name: hello-world-lambda
  • AWS region: (your preferred region)
  • AWS account ID: (your account ID)
  • IAM role name: (your Lambda execution role)
  • Handler path: com.example.lambda.Handler::handleRequest

Testing

After deployment, test your function using the provided curl command:

curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' https://<api-id>.execute-api.<region>.amazonaws.com/post

Expected response:

{
    "statusCode": 200,
    "body": "Hello from AWS Lambda!"
}

Troubleshooting

Common issues:

  1. Build fails: Ensure Java 11 is installed and JAVA_HOME is set correctly
  2. Deployment fails: Verify AWS credentials are configured properly
  3. Runtime error: Check the handler path matches your code
  4. Permission denied: Ensure IAM role has appropriate permissions

Required Permissions

The IAM role needs these permissions:

  • AWSLambdaBasicExecutionRole
  • CloudWatchLogsFullAccess (for logging)

Clean Up

To remove deployed resources:

  1. Delete the Lambda function
  2. Delete the API Gateway
  3. Delete CloudWatch log groups

Additional Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment