Sunday, March 27, 2022

AWS - API Gateway with Lambda

 Step 1: Create a NodeJs Lambda function

  •         Select Lambda service and Click on Create function button
  •         Select Author From Scracth.
  •         Function name : ApiFunc
  •         Runtime: Node.js 14.x
  •         Permission ---> change default execution role
  •         select create new role from AWS policy Template
  •         and provide the role name apifuncrole

 Click on Create function button

Step 2: Use the below code for the Lambda function 

'use strict';

const https = require('https');
exports.handler = async (event) => {
    let dataString = '';

    const response = await new Promise((resolve, reject) => {
        const req = https.get("https://jsonplaceholder.typicode.com/todos/1", function(res) {
          res.on('data', chunk => {
            dataString += chunk;
          });
          res.on('end', () => {
            resolve({
                statusCode: 200,
                body: JSON.stringify(
                        {
                            "data": JSON.parse(dataString).title,
                            "timestamp": new Date()
                        }, null, 4
                    )
            });
          });
        });
       
        req.on('error', (e) => {
          reject({
              statusCode: 500,
              body: 'Something went wrong!'
          });
        });
    });
   
    return response;
};

Then Click on  File--->save and Click on Deploy


Step 3: Create Rest API using API Gateway.

  •       Select API Gateway Service
  •       Click on Create API button
  •       Select RestAPI and click on Build button
  •       Select New API
  •       Api Name: myapi

  Click on Create Api Button.

Step 4: Create a Resource

  •           Select Action--> Create Resource
  •           Resource Name: what-is-my-title

     Click on Create Resource Button

Step 5: Select resource what-is-my-title and Goto Action---> Create Method from Drop down select Get Method and click on tick mark. 

Step 6: Click on Get Method 

  •            Integration Type: Lambda Function
  •           Select check box Use Lambda proxy Integration
  •           Lambda function: <<Lamda function name>> 

Click on Save button

Step 7: Select GET and Goto Action--->Deploy API

            Deployment Stage : New Stage

            Stage Name: api

Click on the Deploy button.

Step 8: You will find one Invoke URL on the top and open that URL in a new tab and at the end of the URL add what-is-my-title

  You will be able to see the title and current date and time

Step 9: Click on Export tab and select the Swagger and select Export as Swagger and click on json. It will download the json file for api Gateway.


Step 9: Take screen shot and copy IAM Role policy 

0 comments:

Post a Comment