Building Restful APIs with Express.js

Introduction

Express.js is a popular Node.js web framework that simplifies the development of web applications. It is used to create server-side applications and APIs that respond to client requests. Building a Restful API with Express.js is straightforward and helps you build scalable, modular and maintainable applications.

This tutorial will guide you through the process of building Restful APIs with Express.js. You will learn the fundamentals of RESTful architecture, how to create RESTful routes in Express.js and how to handle requests and responses.

Prerequisites

Before getting started, you will need to have Node.js and npm installed on your machine. You can download the latest version of Node.js from the official website https://nodejs.org/.

Creating a New Project

First, create a new directory for your project and navigate to that directory using the terminal. Next, initialize a new Node.js project using the following command:

npm init -y

This command will create a new package.json file in the current directory with default values.

Next, install the express package using the following command:

npm install express

This command installs the latest version of the express package and adds it to the dependencies section of the package.json file.

Creating a Server

Now that you have set up your project, you can begin building your Restful API with Express.js. Start by creating an index.js file in the root directory of your project. This file will be the entry point of your application.

Open the index.js file in your favorite code editor and add the following code:

const express = require('express');

const app = express();

const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Listening on port ${port}...`);
});

In this code, you first import the express module. You then create a new express application by calling the express() function. Finally, you specify the port that your server will listen on and start the server by calling the listen() method.

To run your application, open the terminal in the root directory of your project and run the following command:

node index.js

This will start your server on the specified port. You can navigate to http://localhost:3000 in your web browser to check if your server is running correctly.

Routing

Routing is a mechanism in Express.js that allows us to define the structure of our API. Express.js provides a way to define routes for different HTTP requests like GET, POST, PUT and DELETE. Each request method is associated with a specific function that is called when a request is received.

Defining Routes

To define a new route for your API, add the following code to your index.js file:

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

In this code, you define a new route for the root URL (‘/’). This route will be used to handle GET requests. When a GET request is received for the root URL, the callback function (req, res) is called. In this callback function, you send the string ‘Hello world!’ as the response to the client.

Route Parameters

Route parameters are used to extract data from the URL and pass it as an argument to the callback function. To define a route parameter, start the parameter name with a colon(:).

app.get('/users/:id', (req, res) => {
  const id = req.params.id;
  res.send(`User ID: ${id}`);
});

In this code, you define a route parameter :id. You then extract the value of this parameter using req.params.id. Finally, you send the extracted value as a response to the client.

Route Methods

Express.js provides HTTP methods for each route that can be specified using the app.METHOD() functions, where METHOD is the HTTP method of the request that the route handles.

app.post('/users', (req, res) => {
  const user = {
    name: req.body.name,
    email: req.body.email
  };
  // Save the user to the database
  res.send(user);
});

In this code, you define a new route for the URL ‘/users’. This route will be used to handle POST requests. When a POST request is received for the ‘/users’ URL, the callback function (req, res) is called. In this callback function, you extract the name and email fields from the request body and save them to the database. You then send the saved user as a response to the client.

Route Chaining

Route chaining is a mechanism in Express.js that allows us to chain multiple HTTP methods on a single route.

app.route('/users/:id')
  .get((req, res) => {
    const id = req.params.id;
    // Get the user with the ID from the database
    res.send(user);
  })
  .put((req, res) => {
    const id = req.params.id;
    const user = {
      name: req.body.name,
      email: req.body.email
    };
    // Update the user with the ID in the database
    res.send(user);
  })
  .delete((req, res) => {
    const id = req.params.id;
    // Delete the user with the ID from the database
    res.send('User deleted');
  });

In this code, you define a new route for the URL ‘/users/:id’. You then chain multiple HTTP methods on this route to handle GET, PUT and DELETE requests. When a GET request is received for the ‘/users/:id’ URL, the callback function (req, res) is called. In this callback function, you extract the user ID from the URL and retrieve the user with this ID from the database. You then send the retrieved user as a response to the client. Similarly, you handle PUT and DELETE requests by extracting the user ID from the URL, updating or deleting the user from the database and sending an appropriate response to the client.

Middleware

Middleware is a function that sits between the request and response cycle of a server and performs some action on the request before it reaches the response. Middleware can be used for a wide variety of purposes like authentication, logging, error handling, etc.

Creating Middleware

To create middleware, use the app.use() method. This method takes a callback function as an argument that receives the request and response objects as arguments.

app.use((req, res, next) => {
  console.log('Middleware called...');
  next();
});

In this code, you define a new middleware function that logs a message to the console. The next() function is called to pass control to the next middleware in the chain.

Using Middleware in Routes

Middleware can be used in specific routes by passing them as arguments to the app.METHOD() function.

app.get('/users', (req, res, next) => {
  console.log('Middleware called...');
  next();
}, (req, res) => {
  res.send('Users list');
});

In this code, you define a new route for the URL ‘/users’. You then pass a middleware function as the first argument to the app.get() function. This middleware function logs a message to the console. You then define the callback function (req, res) that sends the string ‘Users list’ as the response.

Conclusion

In this tutorial, you learned how to build Restful APIs with Express.js. You learned the fundamentals of RESTful architecture, how to create RESTful routes in Express.js and how to handle requests and responses. You also learned how to use middleware in your application for various purposes like authentication, logging, error handling, etc.

Express.js is a versatile and powerful web framework that simplifies the development of web applications and APIs. It provides a wide range of features that make it easy to create scalable, modular and maintainable applications. With the knowledge you gained from this tutorial, you can start building your own Restful APIs using Express.js.

Related Post