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.
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);
});[{"id":1,"name":"Pen"}]GET returns the full list; POST adds a new item and returns it with status 201.
app.delete('/items/:id', (req, res) => {
items = items.filter(i => i.id != req.params.id);
res.status(204).end();
});204 No ContentDELETE 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.
