A minimal, production-ready "Hello World" AWS Lambda written in Java 21 with API Gateway, structured logging, unit tests, and an AWS SAM template for deployment.
- Java 21 (JDK)
- Maven 3.9+
- AWS CLI configured (aws configure)
- AWS SAM CLI 1.100+
src/main/java/com/example/hello/HelloHandler.java— Lambda handler using API Gateway proxy integrationsrc/main/java/com/example/hello/Json.java— minimal JSON helper using Jacksonsrc/test/java/com/example/hello/HelloHandlerTest.java— JUnit teststemplate.yaml— AWS SAM template (runtime java21)events/hello.json— sample API Gateway event for local testingpom.xml— Maven build with shading for deployable artifact
mvn -q -DskipTests packageThe deployable artifact will be in target/lambda-hello-1.0.0-shaded.jar.
mvn -q testBuild with SAM (uses Maven under the hood):
sam buildInvoke locally with the sample event:
sam local invoke HelloFunction -e events/hello.jsonStart a local API (hot-reload-like loop):
sam local start-apiThen open: http://127.0.0.1:3000/hello?name=Atul
First deploy (guided):
sam deploy --guidedRecommended choices during guided deploy:
- Stack Name:
lambda-java-hello - Region: your preferred region (e.g.,
us-east-1) - Confirm changes before deploy:
y - Save arguments to samconfig.toml:
y
Subsequent deploys become just:
sam build && sam deployAfter deploy, SAM outputs ApiUrl. Example:
https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/Prod/hello
Try: ?name=YourName
- Environment variable
GREETINGcontrols the greeting prefix. Default isHello.- Set in
template.yamlunderGlobals -> Function -> Environment -> Variables.
- Set in
- Uses SLF4J (
org.slf4j:slf4j-simple) for structured logs. - Also writes a short line to the
LambdaLoggerfor quick timing visibility. - View logs via CloudWatch Logs or locally when using
sam local.
- Handler:
com.example.hello.HelloHandler::handleRequest - Input:
APIGatewayProxyRequestEvent - Output:
APIGatewayProxyResponseEvent
- If your IDE shows package mismatch errors like
main.java.com..., import the project as a Maven project. The source layout here is standard Maven (src/main/javaandsrc/test/java). - Java 21 runtime is specified in the SAM template (
java21). Ensure your AWS region supports it.
To remove deployed resources:
aws cloudformation delete-stack --stack-name lambda-java-hello