Node.js ยท Chapter 23 of 43

REST API CRUD Operations

REST APIs organize functionality around resources (like 'users' or 'products') using standard HTTP methods: GET (read), POST (create), PUT/PATCH (update), and DELETE (remove).

A well-designed REST API is predictable โ€” the same URL pattern with different methods handles different operations.

CRUD mapping

GET /items lists items, GET /items/:id gets one, POST /items creates, PUT /items/:id updates, and DELETE /items/:id removes.

In-memory example

For learning, CRUD operations can be demonstrated against a simple in-memory array before introducing a real database.

Example 1 (javascript)
let items = [{ id: 1, name: 'Pen' }];
app.get('/items', (req, res) => res.json(items));
app.post('/items', express.json(), (req, res) => {
  const item = { id: Date.now(), name: req.body.name };
  items.push(item);
  res.status(201).json(item);
});
Output
[{"id":1,"name":"Pen"}]

GET returns the full list; POST adds a new item and returns it with status 201.

Example 2 (javascript)
app.delete('/items/:id', (req, res) => {
  items = items.filter(i => i.id != req.params.id);
  res.status(204).end();
});
Output
204 No Content

DELETE removes a matching item and returns an empty 204 response.

Key points

  • REST maps HTTP methods to CRUD actions.
  • GET reads, POST creates, PUT/PATCH updates, DELETE removes.
  • Status codes matter: 201 Created, 204 No Content, 404 Not Found.
  • Real apps replace in-memory arrays with a database.
๐Ÿ’ก Note: Keep REST URLs noun-based (e.g. /items) rather than verb-based (e.g. /getItems).

๐Ÿ“ Quick Quiz

1. Which HTTP method typically creates a new resource?

2. Which status code indicates successful creation?

3. Which method removes a resource?