Skip to main content

Day 20: Mini Project โ€“ Notes API (with Validation)

Published 4 min readMarkdown
Part of seriesNode.js Mastery: From Basics to Real-world Projects

In this mini project, we will build a Notes API where users can:

  1. Add a new note โœ๏ธ

  2. Get all notes ๐Ÿ“’

  3. Get a single note by ID ๐Ÿ”Ž

  4. Update a note ๐Ÿ“

  5. Delete a note โŒ

๐Ÿ‘‰ Data will be stored in a notes.json file (since we havenโ€™t covered databases yet).
๐Ÿ‘‰ We will also add validation using express-validator so that only valid notes are saved.


๐Ÿ”น Step 1: Project Setup

  1. Create a folder notes-api

  2. Run command:

     npm init -y
     npm install express express-validator
    
  3. Create files:

    • server.js (main entry)

    • routes/notesRoutes.js (all routes here)

    • data/notes.json (to store notes, initially [])


๐Ÿ”น Step 2: Basic Express Server (server.js)

const express = require("express");
const notesRoutes = require("./routes/notesRoutes");

const app = express();
app.use(express.json()); // Middleware to parse JSON

// Use routes
app.use("/api/notes", notesRoutes);

// Start server
app.listen(3000, () => {
  console.log("๐Ÿš€ Server running at http://localhost:3000");
});

๐Ÿ”น Step 3: Notes Routes (routes/notesRoutes.js)

Weโ€™ll use CRUD APIs with validation.

const express = require("express");
const { body, validationResult } = require("express-validator");
const fs = require("fs");
const path = require("path");

const router = express.Router();
const filePath = path.join(__dirname, "../data/notes.json");

// Helper functions
const readNotes = () => JSON.parse(fs.readFileSync(filePath, "utf-8"));
const writeNotes = (data) => fs.writeFileSync(filePath, JSON.stringify(data, null, 2));

/* ---------------- CREATE Note ---------------- */
router.post(
  "/",
  [
    body("title").notEmpty().withMessage("Title is required"),
    body("content").isLength({ min: 5 }).withMessage("Content must be at least 5 characters"),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, errors: errors.array() });
    }

    const notes = readNotes();
    const newNote = {
      id: notes.length + 1,
      title: req.body.title,
      content: req.body.content,
    };

    notes.push(newNote);
    writeNotes(notes);

    res.status(201).json({ success: true, note: newNote });
  }
);

/* ---------------- READ All Notes ---------------- */
router.get("/", (req, res) => {
  const notes = readNotes();
  res.json({ success: true, count: notes.length, notes });
});

/* ---------------- READ Single Note ---------------- */
router.get("/:id", (req, res) => {
  const notes = readNotes();
  const note = notes.find((n) => n.id === parseInt(req.params.id));

  if (!note) {
    return res.status(404).json({ success: false, message: "Note not found" });
  }

  res.json({ success: true, note });
});

/* ---------------- UPDATE Note ---------------- */
router.put(
  "/:id",
  [
    body("title").optional().notEmpty().withMessage("Title cannot be empty"),
    body("content").optional().isLength({ min: 5 }).withMessage("Content must be at least 5 characters"),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, errors: errors.array() });
    }

    const notes = readNotes();
    const noteIndex = notes.findIndex((n) => n.id === parseInt(req.params.id));

    if (noteIndex === -1) {
      return res.status(404).json({ success: false, message: "Note not found" });
    }

    // Update note
    notes[noteIndex] = { ...notes[noteIndex], ...req.body };
    writeNotes(notes);

    res.json({ success: true, note: notes[noteIndex] });
  }
);

/* ---------------- DELETE Note ---------------- */
router.delete("/:id", (req, res) => {
  const notes = readNotes();
  const newNotes = notes.filter((n) => n.id !== parseInt(req.params.id));

  if (notes.length === newNotes.length) {
    return res.status(404).json({ success: false, message: "Note not found" });
  }

  writeNotes(newNotes);
  res.json({ success: true, message: "Note deleted successfully" });
});

module.exports = router;

๐Ÿ”น Step 4: Testing with Postman

  1. Create Note (POST /api/notes)

     {
       "title": "Shopping List",
       "content": "Buy milk, eggs, and bread"
     }
    

    โœ… Response:

     {
       "success": true,
       "note": {
         "id": 1,
         "title": "Shopping List",
         "content": "Buy milk, eggs, and bread"
       }
     }
    

    โŒ Wrong Request:

     {
       "title": "",
       "content": "Hi"
     }
    

    Response:

     {
       "success": false,
       "errors": [
         { "msg": "Title is required", "param": "title" },
         { "msg": "Content must be at least 5 characters", "param": "content" }
       ]
     }
    
  2. Get All Notes (GET /api/notes)

     {
       "success": true,
       "count": 1,
       "notes": [
         {
           "id": 1,
           "title": "Shopping List",
           "content": "Buy milk, eggs, and bread"
         }
       ]
     }
    
  3. Update Note (PUT /api/notes/1)

     {
       "content": "Buy milk, eggs, bread, and butter"
     }
    
  4. Delete Note (DELETE /api/notes/1)


๐Ÿ”น Error Handling in this Project

  • Validation Errors โ†’ Handled with express-validator

  • Not Found Errors โ†’ Checked using conditionals and return 404

  • JSON File Issues โ†’ Handled with try/catch in real projects (optional for now)


๐Ÿ”น Real-Life Connection

This Notes API is a mini version of apps like Google Keep, Evernote, or Notion.
Later, when we learn databases (MongoDB), weโ€™ll store notes there instead of JSON files.


๐Ÿ”น Key Takeaways

  • We built a full CRUD API using Express.

  • We used express-validator to ensure data is valid.

  • We learned to store data in JSON as a database alternative.

  • This project covered:
    โœ… Routes
    โœ… Route params
    โœ… Validation
    โœ… CRUD Operations
    โœ… Error Handling


โœ… Now students can proudly say they have built a real-world Notes API with validation ๐ŸŽ‰


๐Ÿ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas โ€” ๐Ÿ“ฉ Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, ๐ŸŽฅ Donโ€™t forget to subscribe to my YouTube channel โ€“ Knowledge Factory 22 โ€“ for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. ๐Ÿš€

About the author

  • Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: ๐Ÿš€ In-depth explorations of emerging technologies ๐Ÿ’ก Practical tutorials and how-to guides ๐Ÿ”งInsights on software development best practices ๐Ÿš€Reviews of the latest tools and frameworks ๐Ÿ’ก Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letโ€™s connect and grow together! ๐ŸŒŸ

No comments yet. Be the first to comment.

More from this blog