Home / Node.js / Lesson 5

A REST API in memory

Intermediate 10 min read Lesson 5 of 6

REST here means: resources as URLs, HTTP methods for actions, JSON bodies. We store notes in memory so you can run this with zero database setup. Restarting the server clears data — that is honest, not a hidden Mongo install.

import express from 'express';

const app = express();
app.use(express.json());

let notes = [{ id: '1', text: 'Revise OS scheduling' }];

app.get('/notes', (req, res) => res.json(notes));

app.get('/notes/:id', (req, res) => {
  const note = notes.find((n) => n.id === req.params.id);
  if (!note) return res.status(404).json({ error: 'Not found' });
  res.json(note);
});

app.post('/notes', (req, res) => {
  const text = typeof req.body.text === 'string' ? req.body.text.trim() : '';
  if (!text) return res.status(400).json({ error: 'text required' });
  const note = { id: String(Date.now()), text };
  notes.push(note);
  res.status(201).json(note);
});

app.delete('/notes/:id', (req, res) => {
  const before = notes.length;
  notes = notes.filter((n) => n.id !== req.params.id);
  if (notes.length === before) return res.status(404).json({ error: 'Not found' });
  res.status(204).end();
});

app.listen(3000);

Try with curl or Thunder Client:

curl http://localhost:3000/notes
curl -X POST http://localhost:3000/notes -H 'Content-Type: application/json' -d '{"text":"DBMS joins"}'

For a real app you would use SQLite or PostgreSQL. MongoDB is optional, not required to understand REST.