DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Building a RESTful API With AWS Lambda and Express

Building a RESTful API With AWS Lambda and Express

Build a RESTful API using AWS Lambda and Express.js with this quick and easy-to-follow tutorial. Deploy your RESTful API with confidence using Node.js.

Preet Kaur user avatar by
Preet Kaur
·
Mar. 15, 23 · Tutorial
Like (2)
Save
Tweet
Share
3.89K Views

Join the DZone community and get the full member experience.

Join For Free

AWS Lambda is a serverless computing service provided by Amazon Web Services (AWS) that allows you to run code without provisioning or managing servers. Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Together, AWS Lambda and Node.js can be used to create a RESTful API that can be triggered by events such as an HTTP request.

Prerequisites

Before building a RESTful API with Express.js, you should have the following in place:

  1. As Express.js is a JavaScript framework, you’ll need Node.js installed to run it. You can download Node.js from the official website.
  2. Text Editor or Integrated Development Environment (IDE): To write and edit your API code, you will need a text editor or IDE. Examples of popular text editors are Sublime Text and Visual Studio Code, while popular IDEs are WebStorm and Visual Studio.
  3. In order to write your API, you should have a basic understanding of JavaScript, since Express.js is written in JavaScript.
  4. A familiarity with Express.js: Express.js is a web framework for Node.js that helps you build web applications and APIs quickly and easily.
  5. The RESTful APIs use HTTP for communication, so you should be familiar with the protocol. It is necessary to have a basic understanding of HTTP methods (GET, POST, PUT, DELETE) and their intended uses, status codes, and the format of HTTP requests and responses.
  6. For keeping track of changes to your codebase, familiarity with version control systems (VCS) like Git is helpful.

As soon as you have these prerequisites in place, you can start building your RESTful API with Express.js.

Adding in The Code

1. Create an AWS_Node folder using the mkdir command in the terminal and cd into the directory.

mkdir aws-lambda-express-demo
cd aws-lambda-express-demo


2. Create an app.js file in your AWS_Node folder.

touch app.js


Libraries

1. We’ll use npm to download the latest version of the express package from the npm registry and store it in the node_modules folder in your project’s root directory. The package’s dependencies will also be installed and stored there as well.

npm install express


2. Next we’ll install a middleware-compatible framework called serverless-http, a library for creating serverless applications. AWS Lambda allows you to write your application normally, and then wrap it around a function that is exported and executed using an HTTP request. Aside from Azure, Google Cloud, and others, it is also compatible with serverless providers.

npm install serverless-http


You can install the package globally by running npm install -g serverless-http. 

Here’s an example of a RESTful API implemented using Node.js with the Express.js framework that implements the GET, POST, DELETE, and PUT methods:

This code creates an Express.js app and adds routes for the GET, POST, DELETE, and PUT methods. It uses an in-memory items array to store data and uses the find and findIndex methods to retrieve and update items based on the id provided in the URL. Note that for the POST and PUT routes, you will have to parse the body of the request, which you can do with middleware such as body-parser.

const express = require('express');
const app = express();
const serverless = require('serverless-http');
const users = [
    { id: 1, name: 'John', company: "ABC Company" },
    { id: 2, name: 'Frank', company: "XYZ Inc." },
    { id: 3, name: 'Ashley', company: "123 Company" },
];app.get('/users', (req, res) => {
    res.json(users);
});app.get('/users/:id', (req, res) => {
    const user = users.find(user => user.id === parseInt(req.params.id));
    if (!user) res.status(404).json({ message: 'User not found' });
    res.json(user);
});app.post('/users', (req, res) => {
    const user = {
        id: users.length + 1,
        name: req.body.name,
        company: req.body.company,
    };
    users.push(user);
    res.json(user);
});app.delete('/users/:id', (req, res) => {
    const userIndex = users.findIndex(user => user.id === parseInt(req.params.id));
    if (userIndex === -1) res.status(404).json({ message: 'User not found' });
    users.splice(userIndex, 1);
    res.json({ message: 'User deleted' });
});app.put('/users/:id', (req, res) => {
    let user = users.find(user => user.id === parseInt(req.params.id));
    if (!user) res.status(404).json({ message: 'User not found' });
    user.name = req.body.name;
    user.company = req.body.company;
    res.json(user);
});
const handler = serverless(app);const startServer = async () => {
    app.listen(3000, () => {
      console.log("listening on port 3000!");
    });
}startServer();module.exports.handler = (event, context, callback) => {
    const response = handler(event, context, callback);
    return response;
};


We’ll write the line console.log("listening on port 3000!"); to indicate that your API is up and running. Finally, module.exports.handler is a function that takes in event, context, and callback arguments, and calls the handler function passing in the event, context, and callback arguments.

Running and Testing the Code

Start the server by running the following:

node app.js


Now, our API is up and running. You can send a test HTTP request through Postman. By sending a request to localhost:3000/users, you should see a 200 OK status code. For this test, no request body is needed for the incoming request.

Test HTTP request through Postman

API AWS Lambda REST JavaScript

Published at DZone with permission of Preet Kaur. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Getting a Private SSL Certificate Free of Cost
  • How To Build a Spring Boot GraalVM Image
  • Low-Code Development: The Future of Software Development
  • AWS CodeCommit and GitKraken Basics: Essential Skills for Every Developer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: