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.