Skip to content

2. CRUD Operations

1. Simple CRUD Example

Here’s a full CRUD (Create, Read, Update, Delete) example in Express.js using an in-memory array as the data store β€” no database required.

1.1 πŸ“„ server.js

const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON
// In-memory data (acts like a fake DB)
let items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' }
];
// πŸ”Ή CREATE
app.post('/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
// πŸ”Ή READ all
app.get('/items', (req, res) => {
res.json(items);
});
// πŸ”Ή READ one
app.get('/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');
res.json(item);
});
// πŸ”Ή UPDATE
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.json(item);
});
// πŸ”Ή DELETE
app.delete('/items/:id', (req, res) => {
const index = items.findIndex(i => i.id === parseInt(req.params.id));
if (index === -1) return res.status(404).send('Item not found');
const deleted = items.splice(index, 1);
res.json(deleted[0]);
});
// πŸ”Ή Start server
app.listen(3000, () => console.log('Server running on http://localhost:3000'));

1.2 πŸ§ͺ Sample Requests

  • GET /items β†’ List all items
  • GET /items/1 β†’ Get item with id = 1
  • POST /items β†’ Add new item
    { "name": "Orange" }
  • PUT /items/2 β†’ Update item with id = 2
    { "name": "Grapes" }
  • DELETE /items/1 β†’ Delete item with id = 1

1.3 πŸ“ Notes

  • The id is incremented automatically here (simple logic).
  • No database used β€” restarting the server will reset data.
  • Use tools like Postman or cURL to test the API.