Building a RESTful API using Node.js

Posted by

Building a RESTful API using Node.js

Introduction

REST (Representational State Transfer) APIs allow developers to interact with applications without having direct access to the server. By using a HTTP based protocol such as GET, POST, PUT and DELETE, developers can create, read, update and delete data from an application. The RESTful API is a great way for applications to communicate with one another, and Node.js is the perfect server-side platform to build a RESTful API.

Prerequisites

Before you begin building your RESTful API, make sure you have the following prerequisites:

  • Node.js installed on your local machine
  • A text editor (Atom, Sublime Text, etc.)
  • Basic knowledge of JavaScript and the Node.js runtime environment

Setting Up the Project

Once you have the prerequisites installed, you are ready to start building your RESTful API. The first step is to create a project directory and initialize the project. Open up a command line window and navigate to the project directory. Then type the following commands to create the project:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

$ mkdir my-node-project
$ cd my-node-project
$ npm init

[/dm_code_snippet]

This will initialize a Node.js project and create a package.json file. This file will contain information about the project, such as the name and version.

Installing Dependencies

Once the project is initialized, you will need to install the necessary dependencies for your project. For this tutorial, we will be using the Express.js framework and the body-parser module. To install these dependencies, type the following command in the command line:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

$ npm install express body-parser --save

[/dm_code_snippet]

This will install the Express.js framework and the body-parser module, and save the dependencies in the package.json file.

Creating the Server

Now that all the necessary dependencies have been installed, you are ready to create the server. Create a new file in the project directory and name it server.js. Open the file in your text editor and add the following code:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

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

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

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

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

[/dm_code_snippet]

This code will create an Express.js server and set up the body-parser module so that it can parse incoming requests. It will also set the port to either the environment port (if one is set) or port 3000.

Creating the Routes

Now that the server is set up, you can start creating the routes for your API. Routes are used to define the endpoints of the API and the HTTP methods that can be used to access that endpoint. To create the routes, open the server.js file and add the following code:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

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

app.get('/users', (req, res) => {
  res.json({
    users: [
      { name: 'Bob', age: 20 },
      { name: 'John', age: 30 },
      { name: 'Sally', age: 40 }
    ]
  });
});

app.post('/users', (req, res) => {
  const user = req.body;
  // Add user to database
  res.json({
    message: 'User added successfully!'
  });
});

app.put('/users/:id', (req, res) => {
  const user = req.body;
  // Update user in database
  res.json({
    message: 'User updated successfully!'
  });
});

app.delete('/users/:id', (req, res) => {
  // Delete user from database
  res.json({
    message: 'User deleted successfully!'
  });
});

[/dm_code_snippet]

This code will create four routes: GET /, GET /users, POST /users, PUT /users/:id and DELETE /users/:id. The GET / route will return a simple “Hello World!” message, the GET /users route will return a list of users, the POST /users route will add a new user to the database, the PUT /users/:id route will update an existing user, and the DELETE /users/:id route will delete a user from the database.

Testing the API

Now that the server and routes are set up, you can test the API. To do this, open a command line window and start the server by typing the following command:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

$ node server.js

[/dm_code_snippet]

This will start the server and you should see a message that the server is running on port 3000. Now you can test the API using a tool like Postman or cURL. Try making a GET request to the /users endpoint and you should get a list of users.

Conclusion

In this tutorial, you learned how to build a RESTful API using Node.js. You created a server, installed the necessary dependencies, and created routes for the API. Finally, you tested the API using Postman or cURL. Building a RESTful API using Node.js is a great way to make your applications more accessible and allow for easier communication between applications.