DEV Community

Cover image for How to Build a REST API with Node.js and Express
Muhammad Atif Latif
Muhammad Atif Latif Subscriber

Posted on

How to Build a REST API with Node.js and Express

In this tutorial, we'll learn how to create a simple REST API using Node.js and the Express framework. REST APIs are vital for enabling communication between clients and servers, allowing them to interact with data over the web.

Prerequisites

Before we begin, ensure you have the following installed:

  • Node.js: Download and install from [nodejs.org].
  • npm: Comes bundled with Node.js, but make sure it's up to date.

Step 1: Setting Up the Project

  1. Create a new directory for your project:
   mkdir my-api
   cd my-api
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new Node.js project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install Express:
   npm install express
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating Your First Endpoint

Create a file named server.js in your project directory and add the following code:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());

// Simple GET endpoint
app.get('/', (req, res) => {
    res.send('Welcome to my API!');
});

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

Testing the Endpoint

Run your server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Open your browser or Postman and go to http://localhost:3000. You should see "Welcome to my API!".

Step 3: Adding CRUD Functionality

Now, let's implement Create, Read, Update, and Delete operations. For simplicity, we’ll store data in memory.

Sample Data

Add this sample data at the top of your server.js file:

let items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
];
Enter fullscreen mode Exit fullscreen mode

Create an Item

Add the following POST endpoint:

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

Read All Items

Add the following GET endpoint:

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

Update an Item

Add the following PUT endpoint:

app.put('/items/:id', (req, res) => {
    const item = items.find(i => i.id === parseInt(req.params.id));
    if (!item) return res.status(404).send('Item not found.');

    item.name = req.body.name;
    res.send(item);
});
Enter fullscreen mode Exit fullscreen mode

Delete an Item

Add the following DELETE endpoint:

app.delete('/items/:id', (req, res) => {
    const itemIndex = items.findIndex(i => i.id === parseInt(req.params.id));
    if (itemIndex === -1) return res.status(404).send('Item not found.');

    const deletedItem = items.splice(itemIndex, 1);
    res.send(deletedItem);
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Error Handling

To handle errors gracefully, you can add a middleware for 404 errors:

app.use((req, res) => {
    res.status(404).send('Resource not found.');
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You've built a simple REST API using Node.js and Express. You can now expand this API by adding features like authentication, connecting to a database, or implementing advanced error handling.

Further Reading

  • [Express Documentation]
  • [Node.js Documentation]

Feel free to share your thoughts or improvements in the comments below!

Top comments (0)