Deploying a Lambda Function in Kotlin with Serverless

Deploying a simple Lambda function written in Kotlin with custom arguments, using the serverless framework.

Posted by Ricardo Trindade on May 7, 2019

With this simple post, I wanted to show how you can deploy a function written in Kotlin to AWS Lambda using the Serverless framework, with the extra of showing how you can add a custom class to represent the arguments that your function can receive. I'll assume that you are accustomed to using serverless for deploying lambda functions.

First of let's start with the serverless.yml file

  service: kotlin-serverless

  frameworkVersion: ">=1.2.0 <2.0.0"

    artifact: build/distributions/

    name: aws
    runtime: java8
    region: eu-west-1
    profile: test-profile
    timeout: 20
    stage: test

      handler: lambda.Handler::handleRequest

The function will be named web, and has the service is called kotlin-serverless and we are specifying a default profile test, it will show on aws as kotlin-serverless-web-test. The function handler will be the method handlerRequest of the Handler class that lives inside the lambda package (check the code below). The naming is important as if there are some mismatches AWS will fail to run your function. The remaining fields you can just look up on serverless's documentation to understand their meaning.

Now for the Kotlin code itself.

Notice that I'm declaring the package lambda at the top of the file so that AWS can find it. I'm also extending from the base RequestHandler class from Amazon and I'm declaring a RequestClass which represents the arguments that the function will receive. The function will receive those arguments serialized as JSON, so we must create a custom class to map the JSON fields, that the function is expecting.

I'm assuming that the function will be invoked with a payload like:

                  "argInt": 2,
                  "argString": "hello"

So the RequestClass must have the exact names as the arguments that will be in the payload, if not the function will fail to run.

Finally to assemble everything together I declared a gradle task that generates the zip that serverless is going to deploy.

                task buildZip(type: Zip) {
                    from compileKotlin
                    from processResources
                    into('lib') {
                        from configurations.compileClasspath

And that's just it, now you just need to run serverless deploy and the function will be uploaded to AWS.

So what did you think of it? It may be a simple example of a lambda function, but it may serve you as an initial building block for a more complex project! Feel free to hit me up on Twitter with your thoughts and opinions.