Overview Of The AWS Lambda Structure

In the last article, we learned about serverless computing and AWS lambda.

AWS Lambda 
In this article we will dive deep into AWS Lambda and learn its structure along with its execution. How to have handler in the function, that AWS Lambda can then invoke when the service executes your code.

  1. exports.main = function(event, context,) {  
  2.    //TO DO  
  3. }  

The callback parameter is optional depending on whether you want to return information to the caller or not.

  1. exports.main = function(event, context, callback) {  
  2.    // Use callback() and return information to the caller.   
  3. }  

Let’s try to understand the syntax:

  • event – This parameter is used to pass on the event data to the handler. It can be anything like String, JSON object, etc.
  • context – This parameter is used to provide run time information to your lambda function handler. Such as:
    • function name (functionName)
    • logGroupname (logGroupName)
    • logStreamName (logStreamName)
    • remainingTime (getRemainingTimeInMillis)

  • callback – This optional parameter can be used to return any data back to caller, or else return value is null
  • main – This is the name of the function AWS lambda invokes as seen in the “main” example. It can be named anything like main, handler, init etc.

If your code is saved as index.js, then it will be called as index.main, where index is will be your file name (index.js) and main is the entry point function.

e.g.

  1. exports.main = function(event, context, callback) {  
  2.         console.log("value1 = " + event.key1);  
  3.         console.log("value2 = " + event.key2);  
  4.         callback(null"some success message"); // or    // callback("some error type");   
  5. }  

As you can see in the above example, if function wants to return some data without error, null can be passed in the callback or else we need to pass an error object in callback.

The following are different ways callback can be used.

  1. callback();        // Indicates success but no information returned to the caller.  
  2. callback(null); // Indicates success but no information returned to the caller.  
  3. callback(null"success");  // Indicates success with information returned to the caller.  
  4. callback(error);    //  Indicates error with error information returned to the caller.  

There are fewer ways to test and run lambda functions.

  1. Manually upload a lambda function and test it.
  2. AWS CLI
  3. Using AWS API Gateway Endpoint
  4. Using serverless Infrastructure tools which includes smooth deployment/management/invocation etc.

    1. Serverless Framework
    2. Apex
    3. Chalice

Will try to cover a few of them in a later series.

I Hope this article made you understand the code structure of a lambda function and how can it be invoked and managed.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now