Node.js is a robust framework for JavaScript server-side application development. GET, POST, PUT, and DELETE are the fundamental methods of every CRUD (Create, Read, Update, Delete) action, and we'll show you how to create a basic REST API that supports them in this article.

To keep things clear and easy, we'll use the well-liked Express framework.

First, start a Node.js project
To begin, make a new folder for your project and set up npm for it.

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