🎓 Get Full Quality Study Materials & Lab Manuals — Follow our blog using the button below!  |  📺 Subscribe our YouTube Channel "Lectures by Ravula Govardhan" for Programming Contents!  | 
● NEW Experiment 1 to 13 Full Stack Development Lab Programs available Read it here →
“ఈ రోజు నేర్చుకున్న చిన్న విషయం, రేపటి పెద్ద విజయానికి పునాది.”

Notes REST API with Node.js & Express.js – CRUD Example

Experiment · Node.js Lab

Notes REST API using Node.js and Express.js

Aim

To develop a RESTful Notes API using Node.js and Express.js that can create, read, update, and delete notes through HTTP requests.

Procedure

  1. Open a terminal in the project directory.
  2. Install the dependencies using npm init -y and npm install express.
  3. Start the server using node server.js.
  4. Test the endpoints.
  5. Observe the JSON responses returned by the API.

Algorithm

  1. Start the Express server and set up the JSON middleware.
  2. Initialise an in-memory array of note objects.
  3. Define a GET route for the home page to confirm the server is running.
  4. Define a GET route to fetch all notes, and another to fetch a note by ID.
  5. Define a POST route to create a new note, validating that title and content are present.
  6. Define a PUT route to update an existing note by ID.
  7. Define a DELETE route to remove a note by ID.
  8. Return a 404 response whenever a requested note ID does not exist.
  9. Start listening on the configured port.
  10. Stop.
01 Set up the project

Open a terminal in your project folder and run:

Terminal
npm init -y
npm install express
02 Create server.js

Create a file named server.js and add the following code:

server.js
const express = require("express");
const app = express();
const PORT = 5000;

// Middleware
app.use(express.json());

// Notes data
let notes = [
    {
        id: 1,
        title: "Node.js",
        content: "Learn Node.js and Express.js"
    },
    {
        id: 2,
        title: "REST API",
        content: "Learn REST API concepts"
    }
];

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

// GET - Get all notes
app.get("/api/notes", (req, res) => {
    res.json(notes);
});

// GET - Get a note by ID
app.get("/api/notes/:id", (req, res) => {
    const id = Number(req.params.id);
    const note = notes.find(note => note.id === id);

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

    res.json(note);
});

// POST - Create a new note
app.post("/api/notes", (req, res) => {
    const { title, content } = req.body;

    if (!title || !content) {
        return res.status(400).json({
            message: "Title and content are required"
        });
    }

    const newNote = {
        id: notes.length + 1,
        title: title,
        content: content
    };

    notes.push(newNote);

    res.status(201).json({
        message: "Note created successfully",
        note: newNote
    });
});

// PUT - Update a note
app.put("/api/notes/:id", (req, res) => {
    const id = Number(req.params.id);
    const note = notes.find(note => note.id === id);

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

    note.title = req.body.title || note.title;
    note.content = req.body.content || note.content;

    res.json({
        message: "Note updated successfully",
        note: note
    });
});

// DELETE - Delete a note
app.delete("/api/notes/:id", (req, res) => {
    const id = Number(req.params.id);
    const index = notes.findIndex(note => note.id === id);

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

    notes.splice(index, 1);

    res.json({
        message: "Note deleted successfully"
    });
});

// Start server
app.listen(PORT, () => {
    console.log("=================================");
    console.log("Notes REST API Started");
    console.log("Server: http://localhost:5000");
    console.log("=================================");
});
03 Run the server
Terminal
node server.js

The server runs at http://localhost:5000.

Expected Output

=================================
Notes REST API Started
Server: http://localhost:5000
=================================
1 Check API status

Visit localhost:5000 in the browser:



localhost:5000 → "Notes REST API is running successfully!"
2 Get all notes

Visit localhost:5000/api/notes:



localhost:5000/api/notes → JSON array of notes

Result: Thus, a Notes REST API was successfully implemented using Node.js and Express.js. The API was tested successfully for retrieving, creating, updating, and deleting notes, and it also handled an invalid note ID using an appropriate 404 response.

Node.js Express.js REST API CRUD Web Development Lab

0 Ravula Kartheek:

Post a Comment