Skip to content

AWS Serverless Integration

Dawid Kraczkowski edited this page Aug 20, 2021 · 3 revisions

This tutorial relies on serverless framework and assumes you have the following software installed on your local machine:

  • node.js and npm
  • python 3.8 or greater

Setting up the project

pip install poetry
poetry init

Follow the creator steps when asked for defining main dependencies answer no, same for interactively defining dependencies and confirm generation.

npm install -g serverless

The above will install globally serverless framework on your machine

Adding dependencies

poetry add chocs

Setting up serverless

Run below command and follow the prompts

npm init

In next step we will add serverless python requirements to our package.json project, which simplifies packaging and deploying python projects to AWS:

npm add serverless-python-requirements

Generated file should look like the following one:

{
  "name": "serverless-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "serverless-python-requirements": "^5.1.0"
  }
}

Application code

handler.py

import logging
import chocs

logger = logging.getLogger()
logger.setLevel(logging.INFO)
http = chocs.Application()


@http.get("/hello/{name}")
def hello_handler(request: chocs.HttpRequest) -> chocs.HttpResponse:
    logger.info("Hello AWS!")
    return chocs.HttpResponse(f"Hello {request.path_parameters.get('name')}")

__all__ = ["hello_handler"]

Serveless configuration and deployment

serverless.yml

service: aws-hello-name

provider:
  name: aws
  runtime: python3.8

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: true

functions:
  hello_name:
    handler: handler.hello_handler
    events:
      - httpApi:
          method: GET
          path: /hello/{name}

This will register new lambda function hello_name and point it to your python function hello_handler. More detailed documentation how to use and configure serverless application can be found on the serverless framework's documentation.

Last step is deploying our application, make sure your environment variables are correctly configured and run the following command:

serverless deploy

Clone this wiki locally