Serverless Python Selection Sort

While tutoring a student in Python and Java I had the idea of using AWS Lambda to run Python and Java code written by her. The goal was to get her more excited about the code she was writing by having her interact with it on the web.

As an example, I wrote a quick serverless application that accepts a JSON array of unsorted values and returns a sorted array of values. API Gateway validates and transforms the request before sending it to a Python Lambda Function, which sorts the array using Selection Sort. The sorted array is returned to the caller in the body of the response.

API Gateway and Lambda to run Python Selection Sort

Python Lambda Function

The heart of the serverless application is the Lambda Function. The Body Mapping Template in the API Gateway’s Integration Request is providing a Python List of unsorted values, called values, provided by the client. This list is then run through the selection_sort algorithm and returned back to the client as a sorted list of values.

def handler(event, context):
    values = event['values']
    selection_sort(values)
    return values


def selection_sort(arr):
    """
    In-place sort using Selection Sort.

    :param arr: list of values
    :return: None
    """
    if arr is None or len(arr) < 2:
        return arr

    for i in range(len(arr) - 1):
        min_index = i
        for j in range(i+1, len(arr)):
            if arr[j] < arr[min_index]:
                min_index = j
        arr[min_index], arr[i] = arr[i], arr[min_index]

There is also some validation happening in the API Gateway’s Method Request and Method Response sections using JSON Schema, but that’s really it.

cURL

Later I created a Vue.js client for this Lambda Function as part of the AWS CodeStar Credit Challenge, but the student and I used cURL to invoke the API.

curl -H "Content-Type: application/json" \
       -X POST \
       -d '[4, 3, 2]' \
       https://{api}

> [2, 3, 4]

Contents