Build Nodejs RestAPI with Aws Lambda Example Code

Build Restapi with Nodejs & AWS Lambda Example

Here’s an example of how you can build a RESTful API using Node.js and AWS Lambda:

1. Create a new Node.js project by running npm init in your terminal, and then install the necessary packages, such as Express and Body-Parser:

npm install express body-parser

2. Create a new file called index.js and add the following code to set up your Express app and define your routes:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.listen(3000, () => {
    console.log('Server started on port 3000');
});

3. Test your Express app by running node index.js in your terminal and visiting http://localhost:3000 in your browser. You should see “Hello, World!” displayed on the page.

4. Create a new AWS Lambda function by logging into the AWS Management Console, navigating to the Lambda service, and clicking the “Create function” button.

5. In the “Create function” page, select “Author from scratch” and give a name to your function, and also you can choose runtime as Node.js.

6. Create a new deployment package by running the following command in your terminal:

zip -r function.zip *

7. In the AWS Lambda management console, upload the deployment package by clicking on “Upload a .zip file” under the “Function code” section, and then select your zip file.

8. Update the handler in the “Configuration” tab to point to your serverless entry point, in this case is index.handler.

9 .Now you can test your function, for this you can use the test button in the AWS Lambda Management Console.

9. Once your function is working as expected, you can wire it up to an API Gateway to create a fully-fledged RESTful API.

By following this example, you will be able to build a simple RESTful API using Node.js and AWS Lambda, and expose it through an API Gateway. Keep in mind that this is just a basic example, you can add more complex features such as authentication and database integration, to make it a production-ready API.

Deploy Nodejs AWS Lambda with Cloud Formation

AWS CloudFormation is a service that helps you model and set up your Amazon Web Services resources so you can spend less time managing those resources and more time focusing on your applications that run in AWS. With CloudFormation, you can use templates written in YAML or JSON to describe your infrastructure, and then use the AWS Management Console, AWS Command Line Interface (CLI), or SDKs to create, update, and delete your stacks.

Here’s an example of how you can use CloudFormation to deploy a Node.js AWS Lambda function:

1. Create a new CloudFormation template in YAML or JSON, let’s call it template.yml.

2. In the template, define the AWS Lambda function resource. for example:

Resources:
  MyLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Handler: index.handler
      Role: !GetAtt MyIamRole.Arn
      Code:
        ZipFile: !Sub |
          var express = require('express');
          var app = express();

          app.get('/', function (req, res) {
            res.send('Hello World!');
          });

          exports.handler = app;

Here, MyLambdaFunction is the name of the resource. Handler is the name of the exported handler in your code, Role is the IAM role which gives permissions to the function to interact with other AWS services, Code is the code for your lambda function, you can use the ZipFile property with inline code or you can use S3Bucket and S3Key properties if you stored the code in an S3 bucket.

3. In the template, define the IAM Role for the function, for example:

Resources:
  MyIamRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          IpAddress:
            aws:SourceIp:
            - "IP_ADDRESS"
      Path: "/"
      Policies:
      - PolicyName: "root"
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
            StringLike:
              "s3:prefix": "arn:aws:s3:::example-bucket/*"
          Statement:
            StringLike:
              "s3:prefix": "arn:aws:s3:::example-bucket/*"

here you are defining the IAM role that your function is going to use with MyIamRole. AssumeRolePolicyDocument is used to specify permissions that determine who can assume the role. Path is used to set the path for the role, and the Policies used to specify permissions for the role and grant access to resources.

4. Create a new stack in the AWS Management Console, AWS CLI or SDKs.

5. In the CloudFormation section of the AWS Management Console, upload the template.yml file and provide any necessary parameter inputs.

6. Execute the create stack action, CloudFormation will create the Lambda function and IAM role as specified in the template.

RestAPI Nodejs upload file with AWS Lambda example code

Here’s an example of how you can create a RESTful API using Node.js and AWS Lambda that allows you to upload a file:

1. Create a new Node.js project by running npm init in your terminal, and then install the necessary packages, such as Express, Body-Parser, and Multer:

npm install express body-parser multer

2. Create a new file called index.js and add the following code to set up your Express app, configure Multer, and define your routes:

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const app = express();

app.use(bodyParser.json());

const storage = multer.memoryStorage();
const upload = multer({ storage });

app.post('/upload', upload.single('file'), (req, res) => {
    // Do something with the file, for example, save it to S3
    // then return a response
    res.json({ message: 'File uploaded successfully' });
});

exports.handler = app;

3. In the code above, you are creating a new route that listens to a POST request on the /upload endpoint, and it uses the upload.single(‘file’) middleware provided by Multer to handle the uploaded file. The storage is set as memory storage, but you can change it to local storage or S3 depending on your requirement.

4. You can test your Express app by running node index.js in your terminal and sending a POST request to http://localhost:3000/upload with a form-data file.

5. Create a new AWS Lambda function, and upload the deployment package in the same way as the previous example.

6. Update the handler in the “Configuration” tab to point to your serverless entry point, in this case, it is index.handler.

7. Now you can test your function, for this you can use the test button in the AWS Lambda Management Console, or you can wire it up to an API Gateway to create a fully-fledged RESTful API that allows you to upload files.

By following this example, you will be able to create a RESTful API using Node.js and AWS Lambda that allows you to upload a file. Keep in mind that for production, you should consider security and scalability aspect such as using a presigned url to upload files to s3, or you can use S3 events for storing files to S3.

Build Nodejs RestAPI download file with AWS Lambda example code

Here’s an example of how you can create a RESTful API using Node.js and AWS Lambda that allows you to download a file:

1. Create a new Node.js project by running npm init in your terminal, and then install the necessary packages, such as Express and the AWS SDK for JavaScript:

npm install express aws-sdk

2. Create a new file called index.js and add the following code to set up your Express app and define your routes:

const express = require('express');
const AWS = require('aws-sdk');

const app = express();
const s3 = new AWS.S3();

app.get('/download', (req, res) => {
    const s3Params = {
        Bucket: 'your-bucket-name',
        Key: 'path/to/your/file.ext'
    };

    s3.getObject(s3Params, (err, data) => {
        if (err) {
            console.log(err);
            return res.status(500).send(err);
        }
        const file = data.Body;
        res.setHeader('Content-Type', data.ContentType);
        res.setHeader('Content-Disposition', `attachment; filename=${s3Params.Key}`);
        res.send(file);
    });
});

exports.handler = app;

3. In the code above, you are creating a new route that listens to a GET request on the /download endpoint, then it uses the AWS SDK for JavaScript to get the object from the S3 bucket, with the bucket name and the key of the file you want to download.

4. You can test your Express app by running node index.js in your terminal and visiting http://localhost:3000/download in your browser. The file should be downloaded.

5. Create a new AWS Lambda function, and upload the deployment package in the same way as the previous example.

6. Update the handler in the “Configuration” tab to point to your serverless entry point, in this case, it is index.handler.

Aws Nodes Lambda example code

Aws nodes lambda example code

Here is an example of a simple AWS Lambda function written in Node.js that reads a message from an Amazon Simple Queue Service (SQS) queue and processes it:

const AWS = require('aws-sdk');

exports.handler = async (event) => {
  // Get the SQS client
  const sqs = new AWS.SQS();
  
  // Set the queue URL
  const queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-queue';
  
  // Receive a message from the queue
  const response = await sqs.receiveMessage({
    QueueUrl: queueUrl,
  }).promise();
  
  // Get the message body
  const message = response.Messages && response.Messages[0];
  if (message) {
    const body = message.Body;
    
    // Process the message
    console.log('Received message:', body);
    
    // Delete the message from the queue
    await sqs.deleteMessage({
      QueueUrl: queueUrl,
      ReceiptHandle: message.ReceiptHandle,
    }).promise();
    
    // Return the message body
    return body;
  } else {
    // No message was received
    console.log('No message received');
    return null;
  }
};

In this example, the function uses the aws-sdk library to connect to the SQS service and receive a message from the specified queue. The function then processes the message and deletes it from the queue. If no message is received, the function returns null.

To use this function with AWS Lambda, you would need to set up the appropriate IAM roles and policies to allow the Lambda function to access the SQS queue. You would also need to set the queueUrl variable to the correct value for the queue you want to read from.

Once the function is set up and deployed to Lambda, it can be triggered by various events, such as the arrival of a new message in the queue, and the message will be processed and deleted.

Nodejs Aws Lambda with RDS example code

Here is an example of a simple AWS Lambda function written in Node.js that connects to an Amazon Relational Database Service (RDS) database and executes a SQL query:

const AWS = require('aws-sdk');
const mysql = require('mysql2');

exports.handler = async (event) => {
  // Connect to the RDS database
  const connection = mysql.createConnection({
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE,
  });
  
  try {
    // Execute a SQL query
    const [rows] = await connection.promise().query('SELECT * FROM table');
    
    // Return the result
    return rows;
  } finally {
    // Close the connection
    connection.end();
  }
};

In this example, the function uses the mysql2 library to connect to the RDS database using the connection details stored in environment variables. The function then executes a SQL query and returns the result.

To use this function with AWS Lambda, you would need to create an RDS instance and set up the appropriate IAM roles and policies to allow the Lambda function to access the database. You would also need to set the environment variables with the connection details for the RDS instance.

Once the function is set up and deployed to Lambda, it can be triggered by various events, such as an HTTP request or a change in a database, and the result of the SQL query will be returned.

Nodejs Aws Lambda with S3 example code

Here is an example of a simple AWS Lambda function written in Node.js that reads a file from an Amazon Simple Storage Service (S3) bucket and returns the contents:

const AWS = require('aws-sdk');

exports.handler = async (event) => {
  // Get the S3 client
  const s3 = new AWS.S3();
  
  // Set the bucket and file name
  const bucket = 'my-bucket';
  const key = 'path/to/file.txt';
  
  // Read the file from S3
  const response = await s3.getObject({
    Bucket: bucket,
    Key: key,
  }).promise();
  
  // Return the file contents
  return response.Body.toString();
};

In this example, the function uses the aws-sdk library to connect to the S3 service and read the specified file. The file contents are then returned by the function.

To use this function with AWS Lambda, you would need to set up the appropriate IAM roles and policies to allow the Lambda function to access the S3 bucket. You would also need to set the bucket and key variables to the correct values for the bucket and file you want to read.

Once the function is set up and deployed to Lambda, it can be triggered by various events, such as an HTTP request or a change in a database, and the contents of the file will be returned.

Nodejs Aws Lambda with Kinesis Example Code

Here is an example of a simple AWS Lambda function written in Node.js that reads records from an Amazon Kinesis stream and processes them:

const AWS = require('aws-sdk');

exports.handler = async (event) => {
  // Get the Kinesis client
  const kinesis = new AWS.Kinesis();
  
  // Set the stream name and starting sequence number
  const streamName = 'my-stream';
  let startingSequenceNumber = null;
  
  // Process the records in the event
  for (const record of event.Records) {
    // Get the sequence number and data of the record
    const sequenceNumber = record.kinesis.sequenceNumber;
    const data = Buffer.from(record.kinesis.data, 'base64').toString();
    
    // Update the starting sequence number
    if (!startingSequenceNumber || startingSequenceNumber > sequenceNumber) {
      startingSequenceNumber = sequenceNumber;
    }
    
    // Process the record
    console.log('Received record:', sequenceNumber, data);
  }
  
  // Checkpoint the records
  if (startingSequenceNumber) {
    await kinesis.checkpoint({
      ShardId: event.ShardId,
      SequenceNumber: startingSequenceNumber,
      StreamName: streamName,
    }).promise();
  }
};

In this example, the function uses the aws-sdk library to connect to the Kinesis service and processes the records in the event. The function then checkpoints the records to mark them as processed.

To use this function with AWS Lambda, you would need to set up the appropriate IAM roles and policies to allow the Lambda function to access the Kinesis stream. You would also need to set the streamName variable to the correct value for the stream you want to read from.

Once the function is set up and deployed to Lambda, it can be triggered by the Kinesis stream and will process and checkpoint the records as they arrive.

Nodejs Aws Lambda with DynamoDB Example code

Here is an example of a simple AWS Lambda function written in Node.js that reads an item from an Amazon DynamoDB table:

const AWS = require('aws-sdk');

exports.handler = async (event) => {
  // Get the DynamoDB client
  const dynamodb = new AWS.DynamoDB();
  
  // Set the table name and key
  const tableName = 'my-table';
  const key = {
    id: { N: '123' },
  };
  
  // Get the item from the table
  const response = await dynamodb.getItem({
    TableName: tableName,
    Key: key,
  }).promise();
  
  // Return the item
  return response.Item;
};

In this example, the function uses the aws-sdk library to connect to the DynamoDB service and retrieve an item from the specified table using its primary key. The item is then returned by the function.

To use this function with AWS Lambda, you would need to set up the appropriate IAM roles and policies to allow the Lambda function to access the DynamoDB table. You would also need to set the tableName and key variables to the correct values

Node.js/Express RestAPIs – Angular 14 HttpClient – Get/Post/Put/Delete requests + Bootstrap 4

Node.js/Express RestAPIs – Angular 14 HttpClient – Get/Post/Put/Delete requests + Bootstrap 4

Angular provides the HttpClient in @angular/common/http for front-end applications communicate with backend services. In the tutorial, we show how to build an Angular application that uses the HttpClient to make get/post/put/delete requests with Observable apis to Node.js RestAPIs.

Related posts:
Angular 14 Service – with Observable Data for Asynchronous Operation
Angular 14 Routing/Navigation – with Angular Router Service
Angular 14 Template Driven Form – NgModel for Two-Way Data Binding

Continue reading “Node.js/Express RestAPIs – Angular 14 HttpClient – Get/Post/Put/Delete requests + Bootstrap 4”

Angular 14 + Nodejs/Express – Error Handler HttpClient – catchError + retry example

Angular 14 + Nodejs/Express – Error Handler HttpClient – catchError + retry example

In the tutorial, we show how to handle error from Angular HttpClient with catchError & retry when request fails on the server, or in case of a poor network connection.

Related posts:
Node.js/Express RestAPIs – Angular 14 HttpClient – Get/Post/Put/Delete requests + Bootstrap 4

Continue reading “Angular 14 + Nodejs/Express – Error Handler HttpClient – catchError + retry example”

Angular 14 Http Interceptor – with Node.js RestAPIs

Angular provides HTTP Interception to inspect and transform HTTP requests from your application to the server. In the tutorial, we show how to build an Angular 14 Http Log Interceptor with Node.js RestAPIs.

Related posts:
Error Handler Angular 14 HttpClient – catchError + retry – with Node.js/Express example

Continue reading “Angular 14 Http Interceptor – with Node.js RestAPIs”