devnotes.

REST API using the Express to perform CRUD

A REST API exposes Create, Read, Update, and Delete operations over HTTP. Express maps each operation naturally to POST, GET, PUT/PATCH, and DELETE.

Setup

npm install express body-parser

Base server

// app.js
const express = require("express");
const bodyParser = require("body-parser");

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

let notes = [
    { id: 1, text: "Buy groceries" },
    { id: 2, text: "Finish report" },
];

app.get("/", (req, res) => {
    res.send("Notes API is running");
});

app.listen(3500, () => {
    console.log("Server running on http://localhost:3500");
});

Create (POST)

app.post("/notes", (req, res) => {
    const { text } = req.body;
    const newNote = { id: notes.length + 1, text };
    notes.push(newNote);
    res.status(201).json(newNote);
});

Read (GET)

app.get("/notes", (req, res) => {
    res.json(notes);
});

app.get("/notes/:id", (req, res) => {
    const note = notes.find((n) => n.id === parseInt(req.params.id));
    if (!note) return res.status(404).send("Note not found");
    res.json(note);
});

Update (PUT)

app.put("/notes/:id", (req, res) => {
    const note = notes.find((n) => n.id === parseInt(req.params.id));
    if (!note) return res.status(404).send("Note not found");

    note.text = req.body.text;
    res.json(note);
});

Delete (DELETE)

app.delete("/notes/:id", (req, res) => {
    const index = notes.findIndex((n) => n.id === parseInt(req.params.id));
    if (index === -1) return res.status(404).send("Note not found");

    const deleted = notes.splice(index, 1);
    res.json(deleted);
});

Best practices

  • Use the right verb for the operation (GET to read, POST to create, PUT/PATCH to update, DELETE to remove).
  • Parse request bodies with express.json() (or body-parser).
  • Validate input before touching your data store, using something like Joi or express-validator.
  • Prefer resource-oriented URLs, like /notes/:id, over verbs in the path.
REST API using the Express to perform CRUD | DevNotes