RESTful API with NodeJS (ExpressJS)
Tags: webdev, javascript, tutorial, api
Published: 2023-08-07 12:59:23



## **Introduction**

In modern web development, RESTful APIs are essential because they make communication and data exchange between client apps and servers possible. In this article, we'll concentrate on utilizing Express, a popular and compact Node.js web framework, to build a RESTful API. You will get a thorough understanding of building robust and extendable APIs that are capable of managing various CRUD tasks efficiently as you work your way through this lesson.

## **Prerequisites**
Before we begin, make sure you have the following installed on your machine:

- Node.js and npm (Node Package Manager)
- A code editor of your choice (e.g., Visual Studio Code)

## **Getting Started**

**Step 1: Initialize a New Node.js Project**
Open your terminal or command prompt, create a new project folder, and navigate into it. Use the following command to initialize a new Node.js project:

```
npm init -y
```

This will create a `package.json` file, which will store information about your project and its dependencies.

## **Step 2: Install Required Dependencies**
Now we need to install Express, it's a powerful and minimalist web framework, that can help us build our API. Run the following command to install Express:

```
npm install express
```

Additionally, we will use `body-parser` to parse incoming request bodies and `cors` to handle Cross-Origin Resource Sharing (CORS) headers:
```
npm install body-parser cors
```

## **Step 3: Create the Server**

Create a new file named `server.js` in your project folder. This file will serve as the entry point of our API.

```javascript
// Import required modules
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

// Create an instance of Express
const app = express();

// Middleware setup
app.use(bodyParser.json());
app.use(cors());

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

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
```
## **Step 4: Define API Routes**

In this step, we will create routes for handling various API endpoints. For demonstration purposes, we will create routes to handle CRUD operations for a collection of users.

Create a new file named `users.js` inside a folder named routes in your project directory. This file will contain the API routes related to users.

```javascript
const express = require('express');
const router = express.Router();

// Sample user data (temporary)
let users = [
  { id: 1, name: 'John Doe', age: 30 },
  { id: 2, name: 'Jane Smith', age: 25 },
  // Add more users as needed
];

// Get all users
router.get('/users', (req, res) => {
  res.json(users);
});

// Get a single user by ID
router.get('/users/:id', (req, res) => {
  const { id } = req.params;
  const user = users.find((user) => user.id === parseInt(id));

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  res.json(user);
});

// Create a new user
router.post('/users', (req, res) => {
  const { name, age } = req.body;

  // Simple validation
  if (!name || !age) {
    return res.status(400).json({ message: 'Name and age are required' });
  }

  const newUser = { id: users.length + 1, name, age };
  users.push(newUser);

  res.status(201).json(newUser);
});

// Update an existing user by ID
router.put('/users/:id', (req, res) => {
  const { id } = req.params;
  const { name, age } = req.body;

  // Simple validation
  if (!name || !age) {
    return res.status(400).json({ message: 'Name and age are required' });
  }

  const user = users.find((user) => user.id === parseInt(id));

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  user.name = name;
  user.age = age;

  res.json(user);
});

// Delete a user by ID
router.delete('/users/:id', (req, res) => {
  const { id } = req.params;
  users = users.filter((user) => user.id !== parseInt(id));
  res.sendStatus(204);
});

module.exports = router;
```

## **Step 5: Integrate API Routes with the Server**

Back in the `server.js` file, we will integrate the `users.js` routes into our Express application.

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

const app = express();

app.use(bodyParser.json());
app.use(cors());

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

// Import the users routes
const usersRoutes = require('./routes/users');

// Use the users routes
app.use('/api', usersRoutes);

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

## **Conclusion**

In this tutorial, we have covered the step-by-step process of implementing a basic RESTful API in Node.js using ExpressJS. You have learned to create and handle HTTP routes for CRUD operations on user data. With Express Router, the codebase became more organized and maintainable. Throughout the development, you gained hands-on experience in handling HTTP requests, error handling, data parsing, and sending appropriate responses to clients in JSON format.

Congratulations! You have successfully implemented a basic RESTful API in Node.js. Now it's time to test your API endpoints using tools like Postman, cURL or thunder client vs code extension.

My favorite tool for testing API endpoints is `hoppscotch.io` which is open source and you can use for free.