DEV Community

Cover image for Building a RESTful API with AWS Lambda and Express
Xing Wang for moesif

Posted on

Building a RESTful API with AWS Lambda and Express

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 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
Enter fullscreen mode Exit fullscreen mode
  1. Create app.js file in your AWS_Node folder.
touch app.js
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Image description

Wrapping Up

With that, we’ve created a simple RESTful API using AWS Lambda. This code can then be expanded on as needed to build APIs for your applications. Moving forward, you may want to secure the API with an API key, integrate the API with an API gateway, check out how your API is being consumed and used, or build revenue through API monetization? For a solution to your API analytics and monetization needs, check out Moesif today to explore all of this and more!

Oldest comments (0)