Skip to content

A python framework to create micro-services using AWS lambda function

Notifications You must be signed in to change notification settings

noize-e/service-less

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 

Repository files navigation

ServiceLess

A Python framework to work with micro services and AWS lambda function.

Features:

  1. Extendable configuration settings.
  2. C.O.R.S headers validation.
  3. HTTP Requests whitelisting.
  4. Request data verification. 5 Request method function routing.
  5. Exceptions handling.

Config

Settings Default
HTTP_METHODS ['GET', 'POST', 'PUT', 'DELETE', 'HEAD']
HTTP_CONTENT_TYPE 'application/json'
CORS_HEADERS ['Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key', 'x-requested-with']
CORS_ORIGINS '*'
CORS_X_REQUEST '*'

Requests

Routing

For CRUD operations define a handler function using the @route deocorator.
The function name must include the request method as prefix ending with underscore.

from service_less import route

Codes = type('Codes', (,), {
    "OK": 200
})

""" HTTP Method GET"""

@route
def get_handler() -> tuple:
    return ("Hello World", Codes.OK)


""" HTTP Method POST"""
@route
def post_handler(path: str, payload: object) -> tuple:
    return ({
        "post_response": f"Request from '{path}' with payload '{payload}'"
    }, Codes.OK)

Response type: __Tuple(JSON-serializable-object{}, int(2xx | 4xx | 5xx))

Request Whitelist

Allow the method handler function execution by adding the method in the setting list HTTP_METHODS.

# ./config.py
HTTP_METHODS=['GET', 'POST']

Request Handler

The request is expected to came from AWS API Gateway (RESTful API). With the @lambda_func decorator define the main handler functionwith 2 arguments: request-event-object and method-handler-function.

from service_less import route, lambda_func

...

@lambda_func
def lambda_handler(request: dict, handler_func: callable) -> tuple:
    if request.is_post():
        return handler_func(request.path,
                            request.get_payload())
    return handler_func()

Testing

Emulate a request from AWS API Gateway.

from main import lambda_handler


response = lambda_handler({
    "resource": "/url/path",
    "path": "/url/path",
    "httpMethod": "POST",
    "headers": {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "allow": "*",
    },
    "body": f"Hello World!"
}, {})

print(response)

Response:

{
    "statusCode": 200,
    "body": "{\"post_response\": \"Request from '/url/path' with payload 'Hello World!'\"}",
    "headers":
    {
        "X-Requested-With": "*",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
        "Access-Control-Allow-Methods": "GET,POST",
        "Content-Type": "application/json"
    }
}