Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ratamacue/fb6c02099e872f1f79d062fc09fc6f6f to your computer and use it in GitHub Desktop.
Save ratamacue/fb6c02099e872f1f79d062fc09fc6f6f to your computer and use it in GitHub Desktop.
package com.cj.lambda
import collection.JavaConversions._
/**
* This package object wraps the poorly documented AWS API Gateway return value necessary to proper respond to HTTP requests in an
* AWS Lambda Scala project
*/
package object gatewayResponse {
def response(response:ResponseCode, body:String, headers:Map[String, String] = Map()):java.util.Map[String, Object] = {
mapAsJavaMap(Map(
"statusCode"-> response.boxed(),
"headers"-> mapAsJavaMap(headers).asInstanceOf[java.util.Map[java.lang.Integer, java.lang.Float]],
"body"-> body)
).asInstanceOf[java.util.Map[java.lang.String, java.lang.Object]]
}
case class ResponseCode(value:Int){
def boxed() = {
Int.box(value)
}
}
val OK = ResponseCode(200)
}
@ratamacue
Copy link
Author

ratamacue commented Dec 14, 2016

Deploying JVM code to Amazon AWS Lambda with an API Gateway Trigger is poorly documented by Amazon. Most importantly, the API gateway requires a very specific response to no create 500 errors that look like "Execution failed due to configuration error: Malformed Lambda proxy response" or "Internal Server Error". We are required to return a very specific datatype that represents a JSON String before being serialized by Jackson. This is the Scala code that produced the correct map that is required when using the request/response method-handler mechanism such as package.Class::methodToCall.

Usage might look like the following:

package com.cj.demo

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.amazonaws.services.lambda.runtime.Context; 
import com.cj.lambda.gatewayResponse._


class Demo{
  
    def myHandler(context:Context ) = {
      response(OK, "David Says Hello to the Agitators")
    }
     
}

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