← Back to Home

Module 4: AWS Lambda Functions Review

Module Overview

Review AWS Lambda functions and how to effectively test and deploy serverless applications.

Learning Objectives

Code Example: AWS Lambda Function

// Basic AWS Lambda Function Handler
public class MyLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    
    private final DynamoDbClient dynamoDbClient;
    
    // Constructor for dependency injection
    public MyLambdaHandler(DynamoDbClient dynamoDbClient) {
        this.dynamoDbClient = dynamoDbClient;
    }
    
    // Default constructor for AWS Lambda
    public MyLambdaHandler() {
        this(DynamoDbClient.create());
    }
    
    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
        LambdaLogger logger = context.getLogger();
        logger.log("Received event: " + input.getBody());
        
        try {
            // Process the request
            String requestBody = input.getBody();
            MyRequest request = new Gson().fromJson(requestBody, MyRequest.class);
            
            // Perform business logic
            String result = processRequest(request);
            
            // Create success response
            return new APIGatewayProxyResponseEvent()
                .withStatusCode(200)
                .withBody(result)
                .withHeaders(Map.of("Content-Type", "application/json"));
                
        } catch (Exception e) {
            logger.log("Error processing request: " + e.getMessage());
            
            // Create error response
            return new APIGatewayProxyResponseEvent()
                .withStatusCode(500)
                .withBody("{\"error\":\"" + e.getMessage() + "\"}")
                .withHeaders(Map.of("Content-Type", "application/json"));
        }
    }
    
    private String processRequest(MyRequest request) {
        // Actual business logic implementation
        // This could interact with DynamoDB, other AWS services, etc.
        return "Processed request for: " + request.getName();
    }
}

Resources