Home > Uncategorized > Basic #HelloWorld for AWS #Lambda #NodeJS

Basic #HelloWorld for AWS #Lambda #NodeJS

aws_simple_icons_compute_awslambda-svg_

Amazon Lambda allows you to host NodeJS code (And python, Java and c#, I believe) – and expose this as an API. Excellent if you want a scalable back-end without worrying about servers.What they call a “serverless” environment

So, I wanted to create an API that echos back what is posted to it, in NodeJS.

I  created the following service with no authentication with an API gateway trigger

exports.handler = (event, context, callback) => {
if(event.body !== undefined)
{
event = JSON.parse(event.body);
}
var response = {
statusCode: 200,
body: event.key1
};
callback(null, response);
};

Then, you need to find the endpoint, which is under the Triggers tab.

You can then call the endpoint using CURL as follows

curl -H “Content-Type: application/json” -X POST -d “{\”key1\”: \”Echo\”}” https://0vuu0520rb.execute-api.eu-west-1.amazonaws.com/prod/Echo

And you get “Echo” as the response.

Note the line of code, where I check if event.body is null?, that’s because the test environment passes event as a top level element, where as if you use CURL, then event contains other data as follows;

{
  "resource": "\/Echo",
  "path": "\/Echo",
  "httpMethod": "POST",
  "headers": {
    "Accept": "*\/*",
    "CloudFront-Forwarded-Proto": "https",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-Mobile-Viewer": "false",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Tablet-Viewer": "false",
    "CloudFront-Viewer-Country": "GB",
    "Content-Type": "application\/json",
    "Host": "0vuu0520rb.execute-api.eu-west-1.amazonaws.com",
    "User-Agent": "curl\/7.44.0",
    "Via": "1.1 0742a501f4d29312ad9cbc7b7bf143c7.cloudfront.net (CloudFront)",
    "X-Amz-Cf-Id": "XSbyOJGd3tAQI7uSbCyXK_4hbl1gAgskB-bs_R2ICKiznMzxUMbVfw==",
    "X-Amzn-Trace-Id": "Root=1-58ac43b8-4d359d6d43b15ade30527656",
    "X-Forwarded-For": "xxx.xxx.xxx.xxx",
    "X-Forwarded-Port": "443",
    "X-Forwarded-Proto": "https"
  },
  "queryStringParameters": null,
  "pathParameters": null,
  "stageVariables": null,
  "requestContext": {
    "accountId": "005445879168",
    "resourceId": "uzexyk",
    "stage": "prod",
    "requestId": "8ea18e1c-f83b-11e6-9cd3-fdd324d2159e",
    "identity": {
      "cognitoIdentityPoolId": null,
      "accountId": null,
      "cognitoIdentityId": null,
      "caller": null,
      "apiKey": null,
      "sourceIp": "xxx.xxx.xxx.xxx",
      "accessKey": null,
      "cognitoAuthenticationType": null,
      "cognitoAuthenticationProvider": null,
      "userArn": null,
      "userAgent": "curl\/7.44.0",
      "user": null
    },
    "resourcePath": "\/Echo",
    "httpMethod": "POST",
    "apiId": "0vuu0520rb"
  },
  "body": "{event:{\"key1\": \"User\",\"key2\": \"User\",\"key3\": \"User\"}",
  "isBase64Encoded": false
}

All very interesting, now try a more real example, let’s say we want to wrap Google’s direction API within an AWS lamda; – which I’ve implemented as follows;

exports.handler = (event, context, callback) => {
if(event.body !== undefined)
{
event = JSON.parse(event.body);
}
var strUrl = “/maps/api/directions/json?”;
strUrl += “origin=” + event.from;
strUrl += “&destination=” + event.to;
strUrl += “&sensor=false”;
console.log(strUrl);
var https = require(‘https’);

var options = {
host: ‘maps.googleapis.com’,
port: 443,
path: strUrl,
method: ‘GET’,
accept: ‘*/*’
};

var req = https.request(options, function(res) {
var strData = “”;
res.on(‘data’, function(d) {
strData += d;
});
res.on(‘end’, function(d) {
var jData = JSON.parse(strData);
var strSteps = “”;
for(i =0; i<jData.routes[0].legs[0].steps.length;i++)
{
var step = jData.routes[0].legs[0].steps[i];
strSteps += step.html_instructions.replace(/(<([^>]+)>)/ig,” “) + “\r\n”;
}
var response = {
statusCode: 200,
body: strSteps
};
callback(null, response);
console.log(strSteps);
});
});
req.end();

req.on(‘error’, function(e) {
console.error(e);
callback(null, e);
});
};

Which would be called via CURL as follows

curl -H “Content-Type: application/json” -X POST -d “{\”from\”: \”Oxford\”,\”to\”: \”Bristol\”}” https://0vuu0520rb.execute-api.eu-west-1.amazonaws.com/prod/Directions

Which gives the following output

Head north on Shoe Ln
Turn left to stay on Shoe Ln
Turn right onto New Inn Hall St
Turn left onto George St
Continue onto Hythe Bridge St / A4144
At the roundabout, continue straight onto Park End St / A420 Continue to follow A420 Go through 1 roundabout
Turn right to stay on A420
At the roundabout, take the 2nd exit and stay on A420
At the roundabout, take the 2nd exit and stay on A420
At the roundabout, take the 2nd exit and stay on A420
At the roundabout, take the 3rd exit and stay on A420
At Gablecross , take the 2nd exit and stay on A420
At White Hart , take the 1st exit
Take the A419 (South) ramp on the right to M4 / Marlborough / A346 / Chisledon
Merge onto A419
At Badbury Roundabout , take the 3rd exit onto the M4 ramp to South Wales / Bristol / Swindon (W)
Merge onto M4
At junction 19 , exit onto M32 toward Bristol
Continue onto Newfoundland St / A4032 Continue to follow A4032
Slight left onto Temple Way / A4044 Continue to follow A4044
At the roundabout, take the 3rd exit onto Victoria St / B4053
Turn right onto Counterslip
Continue onto Passage St

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: