Create AWS Lambda Function Using Serverless Framework

Earlier I showed how to deploy a Python Lambda Function using the AWS CLI. The serverless framework makes deploying AWS Lambda Functions even easier in my opinion. Let’s quickly deploy a Python Lambda Function to AWS using serverless.

This walktrough assumes you have installed serverless.

Step 1: Create a Pets Service

Create a pets service for AWS using Python 3. This will create a directory called pets with two files: handler.py and serverless.yml.

$ serverless create --template aws-python3 --path pets

Step 2: Configure serverless.yml

I altered the default configuration a bit just to show a few options. I specified my preferred AWS Region, the AWS Lambda defaults for memory and timeout, an existing IAM role in my account, etc.

service: pets

provider:
  name: aws
  runtime: python3.6
  region: us-west-2
  memorySize: 128
  timeout: 3
  role: {my basic lambda execution role arn}

functions:
  ListOfPets:
    handler: handler.main

The AWS Lambda Function being created is called ListOfPets and it’s entry point is a main function.

You could specify events and resources in this configuration file, too, but let’s keep it basic for this tutorial.

Step 3: Write the Python Lambda Function

Serverless provides some default code for Python. I changed it to return an array of pets and called the function main to match the handler specified in serverless.yml.

import json


def main(event, context):
    body = {
        "pets": ["Spike", "Spot"]
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response

Step 4: Deploy the Pets Service to AWS

Deploy the pets service to AWS using serverless. Use the -v (verbose) switch to watch it perform a series of actions to deploy the Lambda Function. It will create a CloudFormation Stack, S3 Bucket, Lambda Function, IAM Role if you don’t specify one, etc.

$ serverless deploy -v

Step 5: Invoke the Lambda Function

Invoke the ListOfPets Lambda Function using serverless.

$ serverless invoke -f ListOfPets

{
    "statusCode": 200,
    "body": "{\"pets\": [\"Spike\", \"Spot\"]}"
}

Step 6: Clean Up Resources

Remove the Lambda Function and all resources used by serverless to deploy it.

$ serverless remove -v

Contents