CRUD Routes

Implement Create, Read, Update and Delete for a resource with an in-memory array.

Syntaxapp.get / post / put / delete

CRUD stands for Create, Read, Update, Delete — the four basic operations on data. The example below implements all of them for a posts resource using a simple array as a stand-in for a database.

Notice how each route maps to a REST convention and returns an appropriate status code.

Example

Example · javascript
app.use(express.json());
let posts = [{ id: 1, title: 'First' }];
let nextId = 2;

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

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

app.post('/posts', (req, res) => {
  const post = { id: nextId++, title: req.body.title };
  posts.push(post);
  res.status(201).json(post);
});

app.delete('/posts/:id', (req, res) => {
  posts = posts.filter(p => p.id !== Number(req.params.id));
  res.status(204).end();
});

When to use it

  • A task manager API exposes POST /tasks to create, GET /tasks/:id to read, PUT /tasks/:id to update, and DELETE /tasks/:id to remove tasks.
  • A team uses an in-memory array as a stand-in data store while building CRUD routes before wiring up the real database.
  • A developer scaffolds all four CRUD routes for a contacts resource in a single Express Router file to keep concerns separated.

More examples

Create and Read

Implements POST (create) and GET (read list + single) using an in-memory array with auto-incrementing IDs.

Example · js
let tasks = [];
let nextId = 1;

app.post('/tasks', (req, res) => {
  const task = { id: nextId++, ...req.body };
  tasks.push(task);
  res.status(201).json(task);
});

app.get('/tasks', (req, res) => res.json(tasks));
app.get('/tasks/:id', (req, res) => {
  const task = tasks.find(t => t.id === Number(req.params.id));
  task ? res.json(task) : res.status(404).json({ error: 'Not found' });
});

Update with PUT

Replaces the full task object at the found index, preserving the original ID while applying all new fields from the body.

Example · js
app.put('/tasks/:id', (req, res) => {
  const idx = tasks.findIndex(t => t.id === Number(req.params.id));
  if (idx === -1) return res.status(404).json({ error: 'Not found' });
  tasks[idx] = { id: tasks[idx].id, ...req.body };
  res.json(tasks[idx]);
});

Delete a resource

Finds the task by ID, removes it from the array with splice, and returns 204 No Content on success.

Example · js
app.delete('/tasks/:id', (req, res) => {
  const idx = tasks.findIndex(t => t.id === Number(req.params.id));
  if (idx === -1) return res.status(404).json({ error: 'Not found' });
  tasks.splice(idx, 1);
  res.status(204).send();
});

Discussion

  • Be the first to comment on this lesson.