Sumit Mukhija

Sitting back watching my code spit 38439246353768 errors.

Write Your First AWS Lambda Function

What is it?

AWS Lambda is an Amazon provided cloud service that lets you compute without provisioning a virtual machine. On account of being serverless, it eliminates the need to manage infrastructure which eventually enables the developers to spend more time to do what they should be doing — develop solutions. 
It also reduces a lot of variabilities that might cause an application to malfunction. At present, you can write lambda functions in Python, Java, Go, and NodeJS. In addition, the cost is calculated based on the execution.

How do I write a lambda function?

Login to your AWS account. If you don’t have one, you can sign up for a free tier. Go to services. Locate or search for Lambda.
You will be presented a Lambda dashboard. You won’t have any lambda function at this point. Click on create function button on the top right.
On the create function screen, select the ‘author from scratch’ option. Give your lambda function a meaningful name. I will write a Python function that returns square of a number. After selecting your preferred runtime and naming the function, click on create function
You will be presented with the code on the subsequent screen when you scroll down a bit. You would see a pre-written lambda handler function which acts as an entry point to your lambda function. This takes two parameters — event and context. You can get data from the event parameter. A lambda function is supposed to return a JSON output.
Further we write a test case. Click on the ‘Test’ button on the top right, give the test a name and provide the key-value pair with the key that you are extracting in your lambda function. Finally, click on ‘create’
Lastly, select the created test event from the dropdown and click on test again. You should see a similar output.
You just wrote your first lambda function. Congratulations!
If you happen to follow along and are looking for the lambda function demonstrated, here it is
import json

def lambda_handler(event, context):
    n = int(event['n'])
    sqr = n ** 2
    return {
        'statusCode': 200,
        'body': json.dumps(sqr)
    }

Tags

Topics of interest