Node.js  

Creating a Basic Node.js REST API (GET, POST, PUT, DELETE)

Node.js is a powerful platform for building server-side applications using JavaScript. In this tutorial, we'll walk you through how to make a simple REST API that supports the core methods of any CRUD (Create, Read, Update, Delete) operation: GET, POST, PUT, and DELETE.

We’ll use the popular Express framework to keep things simple and clean.

Step 1. Initialize a Node.js Project

First, create a new folder for your project and initialize it with npm.

mkdir nodejs-api-demo
cd nodejs-api-demo
npm init -y

Then, install Express,

npm install express

Step 2. Create the API Server

Create a file named server.js and write the following code.

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

app.use(express.json()); // Middleware to parse JSON
let items = []; // Sample in-memory data store
// GET all items
app.get('/api/items', (req, res) => {
    res.json(items);
});
// POST a new item
app.post('/api/items', (req, res) => {
    const newItem = {
        id: Date.now(),
        name: req.body.name
    };
    items.push(newItem);
    res.status(201).json(newItem);
});

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

    if (index !== -1) {
        items[index].name = req.body.name;
        res.json(items[index]);
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// DELETE an item by ID
app.delete('/api/items/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const initialLength = items.length;
    items = items.filter(item => item.id !== id);

    if (items.length < initialLength) {
        res.json({ message: 'Item deleted' });
    } else {
        res.status(404).json({ message: 'Item not found' });
    }
});
// Hello World Endpoint
app.get('/', (req, res) => {
    res.send('Hello, World!');
});
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

Step 3. Run Your API

Start your server using.

node server.js

Open your browser and go to:http://localhost:3000/ You should see "Hello, World!"

Use tools like Postman, Insomnia, or curl to test other endpoints:

  • GET http://localhost:3000/api/items
  • POST http://localhost:3000/api/items with JSON body: { "name": "Apple" }
  • PUT http://localhost:3000/api/items/123456789 with JSON: { "name": "Banana" }
  • DELETE http://localhost:3000/api/items/123456789

Summary

In this tutorial, you learned how to.

  • Initialize a Node.js project
  • Install and use Express.js
  • This setup is great for learning. For production, consider connecting to a real database, such as MongoDB, PostgreSQL, or MySQL.
  • Handle JSON data and HTTP methods (GET, POST, PUT, DELETE)
  • Build a basic in-memory CRUD API