DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

How to Create a REST API with Node.js and Express.js (for Beginners)

Building a REST API is a fundamental skill for backend development. In this article, I’ll walk through how to create a simple REST API using Node.js and Express.js. This guide will provide you with a clear, step-by-step process to build your first API.

NOTE: This tutorial does not integrate any database instead it uses an In-memory array


What is a REST API?

A REST API (Representational State Transfer Application Programming Interface) is a set of rules and conventions for building and interacting with web services. It uses HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources, typically returning data in JSON format.


Prerequisites

Before we begin, make sure you have the following installed:

  1. Node.js: Download and install it from nodejs.org.
  2. A Code Editor: Use any editor you prefer, such as Visual Studio Code, Sublime Text, or Atom.
  3. Postman (optional): A tool to test your API endpoints. Download it from postman.com.

Step 1: Set Up Your Project

1. Create a Project Directory

Open your terminal and create a new directory for your project:

mkdir my-rest-api
cd my-rest-api
Enter fullscreen mode Exit fullscreen mode

2. Initialize a Node.js Project

Run the following command to create a package.json file:

npm init -y
Enter fullscreen mode Exit fullscreen mode

The -y flag automatically fills in default values for your project.


Step 2: Install Required Packages

1. Install Express.js

Express.js is a lightweight web framework for Node.js. Install it using:

npm install express
Enter fullscreen mode Exit fullscreen mode

2. Install Nodemon (Optional)

Nodemon automatically restarts your server whenever you make changes to your code. Install it as a development dependency:

npm install --save-dev nodemon
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the Basic Server

1. Create an index.js File

In your project directory, create a file named index.js:

touch index.js
Enter fullscreen mode Exit fullscreen mode

2. Set Up the Server

Open index.js and add the following code:

// Import the express module
const express = require('express');

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

// Define the port number
const PORT = 3000;

// Middleware to parse JSON bodies
app.use(express.json());

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

// Start the server and listen on the specified port
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

3. Run the Server

Start the server using:

node index.js
Enter fullscreen mode Exit fullscreen mode

If you installed Nodemon, use:

npx nodemon index.js
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser, and you should see "Hello, World!".


Step 4: Add CRUD Operations

Let’s create a simple REST API for managing a list of items. We’ll use an in-memory array to store the data.

1. Create an In-Memory Array

Add this line after app.use(express.json());:

let items = [];
Enter fullscreen mode Exit fullscreen mode

2. Define CRUD Routes

GET /items: Get All Items

app.get('/items', (req, res) => {
    res.json(items);
});
Enter fullscreen mode Exit fullscreen mode

GET /items/:id: Get a Single Item by ID

app.get('/items/:id', (req, res) => {
    const itemId = parseInt(req.params.id);
    const item = items.find(i => i.id === itemId);
    if (!item) {
        return res.status(404).json({ message: 'Item not found' });
    }
    res.json(item);
});
Enter fullscreen mode Exit fullscreen mode

POST /items: Create a New Item

app.post('/items', (req,res) => {
    const newItem = {
        id: items.length + 1,
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json({message:'Item added successful',data:newItem});
});
Enter fullscreen mode Exit fullscreen mode

PUT /items/:id: Update an Item by ID

app.put('/items/:id', (req, res) => {
    const itemId = parseInt(req.params.id);
    const item = items.find(i => i.id === itemId);

    // Check if the item exists
    if (!item) {
        return res.status(404).json({ message: 'Item not found' });
    }

    // Update the item's name
    item.name = req.body.name;

    // Return the updated item
    res.json(item);
});
Enter fullscreen mode Exit fullscreen mode

DELETE /items/:id: Delete an Item by ID

app.delete('/items/:id', (req, res) => {
    const itemId = parseInt(req.params.id);
    const itemIndex = items.findIndex(i => i.id === itemId);
    if (itemIndex === -1) {
        return res.status(404).json({ message: 'Item not found' });
    }
    items.splice(itemIndex, 1);
    res.status(204).send();
});
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Your API

Use Postman or cURL to test your API endpoints:

  1. GET http://localhost:3000/items – Retrieve all items.
  2. POST http://localhost:3000/items – Create a new item. Send a JSON body like { "name": "Item 1" }.
  3. GET http://localhost:3000/items/1 – Retrieve a single item by ID.
  4. PUT http://localhost:3000/items/1 – Update an item. Send a JSON body like { "name": "Updated Item 1" }.
  5. DELETE http://localhost:3000/items/1 – Delete an item by ID.

Step 6: Add Error Handling (Optional)

To handle errors globally, add this middleware at the end of your index.js file:

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ message: 'Something went wrong!' });
});
Enter fullscreen mode Exit fullscreen mode

Step 7: Organize Your Code (Optional)

As your project grows, you can organize your code into separate files and folders. For example:

  • routes/: Define routes.
  • controllers/: Handle business logic.
  • models/: Define data structures.

Final Code

Here’s the complete index.js file:

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

let items = [];

// GET all items
app.get('/items', (req, res) => {
    res.json(items);
});

// GET a single item by ID
app.get('/items/:id', (req, res) => {
    const itemId = parseInt(req.params.id);
    const item = items.find(i => i.id === itemId);
    if (!item) {
        return res.status(404).json({ message: 'Item not found' });
    }
    res.json(item);
});

// POST a new item
app.post('/items', (req,res) => {
    const newItem = {
        id: items.length + 1,
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json({message:'Item added successful',data:newItem});
});

// PUT (update) an item by ID
app.put('/items/:id', (req, res) => {
    const itemId = parseInt(req.params.id);
    const item = items.find(i => i.id === itemId);

    // Check if the item exists
    if (!item) {
        return res.status(404).json({ message: 'Item not found' });
    }

    // Update the item's name
    item.name = req.body.name;

    // Return the updated item
    res.json(item);
});

// DELETE an item by ID
app.delete('/items/:id', (req, res) => {
    const itemId = parseInt(req.params.id);
    const itemIndex = items.findIndex(i => i.id === itemId);
    if (itemIndex === -1) {
        return res.status(404).json({ message: 'Item not found' });
    }
    items.splice(itemIndex, 1);
    res.status(204).send();
});

// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ message: 'Something went wrong!' });
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You’ve built a simple REST API using Node.js and Express.js. This is just the beginning—there’s so much more you can do, like integrating a database, adding authentication, or deploying your API to the cloud.

Keep experimenting, and happy coding!

Top comments (0)