Lambda functions are a great way to put small workloads into the cloud without needing to care about servers or scalability.

They work well with Python and the data format you’ll most likely be using to exchange data is JSON.

This is a very brief post to show how to do this in Python, in particular how to pass JSON data to the lambda function and how to read the JSON result.

The library to use is called boto3 and can be installed with pip install boto3.

Let’s have a very pointless lambda function which takes the name of a user and returns it with some additional data back as JSON:

def handler(event, context):
    user = event.get('user_name', None)

    if user is None:
        raise Exception('Please provide a user.')

    return {
        'hello': 'world',
        'user': user
    }

Alright, easy enough. And here is how you would call it, pass the name and get the response back:

import boto3

def get_from_lambda():
    lambda_client = boto3.client('lambda')
    lambda_dict = {'user': 'hans_peter'}
    result = lambda_client.invoke(
        FunctionName='testfunction',
        InvocationType='RequestResponse',
        LogType='Tail',
        Payload=json.dumps(lambda_dict).encode('utf-8')
    )
    return json.loads(result['Payload'].read().decode())

If you want a more complete example involving machine learning with a lambda function, then check out my post PyTorch Model in Production as a Serverless REST API.