<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Logical Bee</title>
    <link>https://logicalbee.in/</link>
    <description></description>
    <pubDate>Wed, 08 Apr 2026 01:50:59 +0530</pubDate>
    <item>
      <title>Building a RESTful API with Node.js and Express</title>
      <link>https://logicalbee.in/building-a-restful-api-with-node-js-and-express</link>
      <description>&lt;![CDATA[style&#xA;/ Just a minimal style to make this post look good /&#xA;.blog-post-meta {&#xA;  color: #666;&#xA;  font-style: italic;&#xA;  margin-bottom: 2em;&#xA;}&#xA;/style&#xA;&#xA;div class=&#34;blog-post-meta&#34;&#xA;  Posted on September 14, 2025 • 8 min read&#xA;/div&#xA;&#xA;In this tutorial, we&#39;ll walk through building a simple RESTful API using Node.js and Express. This example demonstrates how our enhanced styling for code blocks and images works.&#xA;!--more--&#xA;&#xA;Prerequisites&#xA;&#xA;Before we begin, make sure you have the following installed:&#xA;&#xA;Node.js (v14 or later)&#xA;npm (v6 or later)&#xA;A code editor (VS Code recommended)&#xA;&#xA;Setting Up the Project&#xA;Let&#39;s start by creating a new project directory and initializing it:&#xA;div id=&#34;terminal-setup&#34;/div&#xA;script&#xA;// This will be replaced by the actual terminal creation code&#xA;// when the custom JS is loaded&#xA;/script&#xA;&#xA;The above commands create a new directory for our project, initialize a new npm package, and install Express.&#xA;&#xA;Project Structure&#xA;&#xA;Here&#39;s how our project structure will look:&#xA;rest-api-example/&#xA;  ├── node_modules/&#xA;  ├── src/&#xA;  │   ├── controllers/&#xA;  │   │   └── userController.js&#xA;  │   ├── models/&#xA;  │   │   └── userModel.js&#xA;  │   ├── routes/&#xA;  │   │   └── userRoutes.js&#xA;  │   └── server.js&#xA;  ├── package.json&#xA;  └── package-lock.json&#xA;&#xA;Project structure in VS Code&#xA;&#xA;script&#xA;// This will be replaced with the caption code when the custom JS is loaded&#xA;/script&#xA;&#xA;Creating the Server&#xA;&#xA;First, let&#39;s create our main server file. Create a file at src/server.js with the following code:&#xA;&#xA;const express = require(&#39;express&#39;);&#xA;const app = express();&#xA;const PORT = process.env.PORT || 3000;&#xA;&#xA;// Middleware&#xA;app.use(express.json());&#xA;app.use(express.urlencoded({ extended: true }));&#xA;&#xA;// Routes&#xA;app.get(&#39;/&#39;, (req, res) =  {&#xA;  res.json({ message: &#39;Welcome to our API&#39; });&#xA;});&#xA;&#xA;// Import user routes&#xA;const userRoutes = require(&#39;./routes/userRoutes&#39;);&#xA;app.use(&#39;/api/users&#39;, userRoutes);&#xA;&#xA;// Error handling middleware&#xA;app.use((err, req, res, next) =  {&#xA;  console.error(err.stack);&#xA;  res.status(500).json({&#xA;    error: true,&#xA;    message: &#39;Internal Server Error&#39;&#xA;  });&#xA;});&#xA;&#xA;// Start server&#xA;app.listen(PORT, () =  {&#xA;  console.log(Server running on port ${PORT});&#xA;});&#xA;&#xA;module.exports = app;&#xA;&#xA;Creating the User Model&#xA;&#xA;Next, let&#39;s create a simple user model in src/models/userModel.js:&#xA;&#xA;// This is a simple in-memory model for demonstration&#xA;// In a real application, you would use a database&#xA;&#xA;const users = [&#xA;  { id: 1, name: &#39;John Doe&#39;, email: &#39;john@example.com&#39; },&#xA;  { id: 2, name: &#39;Jane Smith&#39;, email: &#39;jane@example.com&#39; }&#xA;];&#xA;&#xA;class UserModel {&#xA;  findAll() {&#xA;    return Promise.resolve(users);&#xA;  }&#xA;&#xA;  findById(id) {&#xA;    const user = users.find(user =  user.id === parseInt(id));&#xA;    return Promise.resolve(user || null);&#xA;  }&#xA;&#xA;  create(userData) {&#xA;    const newUser = {&#xA;      id: users.length + 1,&#xA;      ...userData&#xA;    };&#xA;    users.push(newUser);&#xA;    return Promise.resolve(newUser);&#xA;  }&#xA;&#xA;  update(id, userData) {&#xA;    const index = users.findIndex(user =  user.id === parseInt(id));&#xA;    if (index === -1) return Promise.resolve(null);&#xA;    &#xA;    const updatedUser = { ...users[index], ...userData };&#xA;    users[index] = updatedUser;&#xA;    return Promise.resolve(updatedUser);&#xA;  }&#xA;&#xA;  delete(id) {&#xA;    const index = users.findIndex(user =  user.id === parseInt(id));&#xA;    if (index === -1) return Promise.resolve(false);&#xA;    &#xA;    users.splice(index, 1);&#xA;    return Promise.resolve(true);&#xA;  }&#xA;}&#xA;&#xA;module.exports = new UserModel();&#xA;&#xA;User Controller&#xA;&#xA;Now, let&#39;s create a controller to handle the business logic in src/controllers/userController.js:&#xA;&#xA;const UserModel = require(&#39;../models/userModel&#39;);&#xA;&#xA;class UserController {&#xA;  async getAllUsers(req, res, next) {&#xA;    try {&#xA;      const users = await UserModel.findAll();&#xA;      res.json(users);&#xA;    } catch (error) {&#xA;      next(error);&#xA;    }&#xA;  }&#xA;&#xA;  async getUserById(req, res, next) {&#xA;    try {&#xA;      const user = await UserModel.findById(req.params.id);&#xA;      if (!user) {&#xA;        return res.status(404).json({ message: &#39;User not found&#39; });&#xA;      }&#xA;      res.json(user);&#xA;    } catch (error) {&#xA;      next(error);&#xA;    }&#xA;  }&#xA;&#xA;  async createUser(req, res, next) {&#xA;    try {&#xA;      const { name, email } = req.body;&#xA;      &#xA;      if (!name || !email) {&#xA;        return res.status(400).json({ message: &#39;Name and email are required&#39; });&#xA;      }&#xA;      &#xA;      const newUser = await UserModel.create({ name, email });&#xA;      res.status(201).json(newUser);&#xA;    } catch (error) {&#xA;      next(error);&#xA;    }&#xA;  }&#xA;&#xA;  async updateUser(req, res, next) {&#xA;    try {&#xA;      const updatedUser = await UserModel.update(req.params.id, req.body);&#xA;      if (!updatedUser) {&#xA;        return res.status(404).json({ message: &#39;User not found&#39; });&#xA;      }&#xA;      res.json(updatedUser);&#xA;    } catch (error) {&#xA;      next(error);&#xA;    }&#xA;  }&#xA;&#xA;  async deleteUser(req, res, next) {&#xA;    try {&#xA;      const success = await UserModel.delete(req.params.id);&#xA;      if (!success) {&#xA;        return res.status(404).json({ message: &#39;User not found&#39; });&#xA;      }&#xA;      res.status(204).end();&#xA;    } catch (error) {&#xA;      next(error);&#xA;    }&#xA;  }&#xA;}&#xA;&#xA;module.exports = new UserController();&#xA;&#xA;Defining Routes&#xA;&#xA;Now let&#39;s set up our routes in src/routes/userRoutes.js:&#xA;&#xA;const express = require(&#39;express&#39;);&#xA;const router = express.Router();&#xA;const UserController = require(&#39;../controllers/userController&#39;);&#xA;&#xA;// GET all users&#xA;router.get(&#39;/&#39;, UserController.getAllUsers);&#xA;&#xA;// GET user by ID&#xA;router.get(&#39;/:id&#39;, UserController.getUserById);&#xA;&#xA;// POST new user&#xA;router.post(&#39;/&#39;, UserController.createUser);&#xA;&#xA;// PUT update user&#xA;router.put(&#39;/:id&#39;, UserController.updateUser);&#xA;&#xA;// DELETE user&#xA;router.delete(&#39;/:id&#39;, UserController.deleteUser);&#xA;&#xA;module.exports = router;&#xA;&#xA;Testing the API&#xA;&#xA;Let&#39;s test our API with some HTTP requests. You can use tools like Postman, curl, or even a simple fetch in the browser.&#xA;&#xA;Testing API with Postman&#xA;&#xA;script&#xA;// This will be replaced with the caption code when the custom JS is loaded&#xA;/script&#xA;&#xA;Here&#39;s a sample curl command to get all users:&#xA;&#xA;div id=&#34;terminal-curl&#34;/div&#xA;script&#xA;// This will be replaced by the actual terminal creation code&#xA;// when the custom JS is loaded&#xA;/script&#xA;&#xA;Conclusion&#xA;&#xA;We&#39;ve built a simple RESTful API using Node.js and Express! This example demonstrates:&#xA;&#xA;Setting up an Express server&#xA;Creating routes&#xA;Implementing controllers&#xA;Building a simple data model&#xA;&#xA;In a real-world application, you would want to add:&#xA;&#xA;Database integration (MongoDB, PostgreSQL, etc.)&#xA;Authentication and authorization&#xA;Input validation&#xA;Testing&#xA;Documentation&#xA;&#xA;Next Steps&#xA;&#xA;Try extending this API with:&#xA;&#xA;Adding more endpoints&#xA;Implementing search functionality&#xA;Adding authentication with JWT&#xA;Connecting to a real database&#xA;&#xA;Happy coding!&#xA;&#xA;script&#xA;// When the custom JS is loaded, this will create our terminal examples&#xA;if (typeof createTerminal === &#39;function&#39;) {&#xA;  document.getElementById(&#39;terminal-setup&#39;).appendChild(&#xA;    createTerminal([&#xA;      { type: &#39;command&#39;, text: &#39;mkdir rest-api-example&#39; },&#xA;      { type: &#39;command&#39;, text: &#39;cd rest-api-example&#39; },&#xA;      { type: &#39;command&#39;, text: &#39;npm init -y&#39; },&#xA;      { type: &#39;output&#39;, text: &#39;Wrote to package.json:\n{\n  &#34;name&#34;: &#34;rest-api-example&#34;,\n  &#34;version&#34;: &#34;1.0.0&#34;,\n  ...\n}&#39; },&#xA;      { type: &#39;command&#39;, text: &#39;npm install express&#39; },&#xA;      { type: &#39;output&#39;, text: &#39;added 57 packages, and audited 58 packages in 3s\n\n3 packages are looking for funding\n  run npm fund for details\n\nfound 0 vulnerabilities&#39; },&#xA;      { type: &#39;command&#39;, text: &#39;mkdir -p src/controllers src/models src/routes&#39; }&#xA;    ])&#xA;  );&#xA;  &#xA;  document.getElementById(&#39;terminal-curl&#39;).appendChild(&#xA;    createTerminal([&#xA;      { type: &#39;command&#39;, text: &#39;curl http://localhost:3000/api/users&#39; },&#xA;      { type: &#39;output&#39;, text: &#39;[\n  {\n    &#34;id&#34;: 1,\n    &#34;name&#34;: &#34;John Doe&#34;,\n    &#34;email&#34;: &#34;john@example.com&#34;\n  },\n  {\n    &#34;id&#34;: 2,\n    &#34;name&#34;: &#34;Jane Smith&#34;,\n    &#34;email&#34;: &#34;jane@example.com&#34;\n  }\n]&#39; }&#xA;    ])&#xA;  );&#xA;  &#xA;  // Add captions to our images&#xA;  const images = document.querySelectorAll(&#39;img&#39;);&#xA;  if (typeof addCaptionToImage === &#39;function&#39;) {&#xA;    addCaptionToImage(images[0], &#39;Project structure organized in folders for better maintainability&#39;);&#xA;    addCaptionToImage(images[1], &#39;Testing the API endpoints with Postman for verification&#39;);&#xA;  }&#xA;}&#xA;/script]]&gt;</description>
      <content:encoded><![CDATA[

<div class="blog-post-meta">
  Posted on September 14, 2025 • 8 min read
</div>

<p>In this tutorial, we&#39;ll walk through building a simple RESTful API using Node.js and Express. This example demonstrates how our enhanced styling for code blocks and images works.
</p>

<h2 id="prerequisites">Prerequisites</h2>

<p>Before we begin, make sure you have the following installed:</p>
<ul><li>Node.js (v14 or later)</li>
<li>npm (v6 or later)</li>
<li>A code editor (VS Code recommended)</li></ul>

<h2 id="setting-up-the-project">Setting Up the Project</h2>

<p>Let&#39;s start by creating a new project directory and initializing it:
<div id="terminal-setup"></div>
</p>

<p>The above commands create a new directory for our project, initialize a new npm package, and install Express.</p>

<h2 id="project-structure">Project Structure</h2>

<p>Here&#39;s how our project structure will look:</p>

<pre><code>rest-api-example/
  ├── node_modules/
  ├── src/
  │   ├── controllers/
  │   │   └── userController.js
  │   ├── models/
  │   │   └── userModel.js
  │   ├── routes/
  │   │   └── userRoutes.js
  │   └── server.js
  ├── package.json
  └── package-lock.json
</code></pre>

<p><img src="https://images.unsplash.com/photo-1579403124614-197f69d8187b?auto=format&amp;fit=crop&amp;w=800&amp;q=80" alt="Project structure in VS Code"></p>



<h2 id="creating-the-server">Creating the Server</h2>

<p>First, let&#39;s create our main server file. Create a file at <code>src/server.js</code> with the following code:</p>

<pre><code class="language-javascript">const express = require(&#39;express&#39;);
const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.get(&#39;/&#39;, (req, res) =&gt; {
  res.json({ message: &#39;Welcome to our API&#39; });
});

// Import user routes
const userRoutes = require(&#39;./routes/userRoutes&#39;);
app.use(&#39;/api/users&#39;, userRoutes);

// Error handling middleware
app.use((err, req, res, next) =&gt; {
  console.error(err.stack);
  res.status(500).json({
    error: true,
    message: &#39;Internal Server Error&#39;
  });
});

// Start server
app.listen(PORT, () =&gt; {
  console.log(`Server running on port ${PORT}`);
});

module.exports = app;
</code></pre>

<h2 id="creating-the-user-model">Creating the User Model</h2>

<p>Next, let&#39;s create a simple user model in <code>src/models/userModel.js</code>:</p>

<pre><code class="language-javascript">// This is a simple in-memory model for demonstration
// In a real application, you would use a database

const users = [
  { id: 1, name: &#39;John Doe&#39;, email: &#39;john@example.com&#39; },
  { id: 2, name: &#39;Jane Smith&#39;, email: &#39;jane@example.com&#39; }
];

class UserModel {
  findAll() {
    return Promise.resolve(users);
  }

  findById(id) {
    const user = users.find(user =&gt; user.id === parseInt(id));
    return Promise.resolve(user || null);
  }

  create(userData) {
    const newUser = {
      id: users.length + 1,
      ...userData
    };
    users.push(newUser);
    return Promise.resolve(newUser);
  }

  update(id, userData) {
    const index = users.findIndex(user =&gt; user.id === parseInt(id));
    if (index === -1) return Promise.resolve(null);
    
    const updatedUser = { ...users[index], ...userData };
    users[index] = updatedUser;
    return Promise.resolve(updatedUser);
  }

  delete(id) {
    const index = users.findIndex(user =&gt; user.id === parseInt(id));
    if (index === -1) return Promise.resolve(false);
    
    users.splice(index, 1);
    return Promise.resolve(true);
  }
}

module.exports = new UserModel();
</code></pre>

<h2 id="user-controller">User Controller</h2>

<p>Now, let&#39;s create a controller to handle the business logic in <code>src/controllers/userController.js</code>:</p>

<pre><code class="language-javascript">const UserModel = require(&#39;../models/userModel&#39;);

class UserController {
  async getAllUsers(req, res, next) {
    try {
      const users = await UserModel.findAll();
      res.json(users);
    } catch (error) {
      next(error);
    }
  }

  async getUserById(req, res, next) {
    try {
      const user = await UserModel.findById(req.params.id);
      if (!user) {
        return res.status(404).json({ message: &#39;User not found&#39; });
      }
      res.json(user);
    } catch (error) {
      next(error);
    }
  }

  async createUser(req, res, next) {
    try {
      const { name, email } = req.body;
      
      if (!name || !email) {
        return res.status(400).json({ message: &#39;Name and email are required&#39; });
      }
      
      const newUser = await UserModel.create({ name, email });
      res.status(201).json(newUser);
    } catch (error) {
      next(error);
    }
  }

  async updateUser(req, res, next) {
    try {
      const updatedUser = await UserModel.update(req.params.id, req.body);
      if (!updatedUser) {
        return res.status(404).json({ message: &#39;User not found&#39; });
      }
      res.json(updatedUser);
    } catch (error) {
      next(error);
    }
  }

  async deleteUser(req, res, next) {
    try {
      const success = await UserModel.delete(req.params.id);
      if (!success) {
        return res.status(404).json({ message: &#39;User not found&#39; });
      }
      res.status(204).end();
    } catch (error) {
      next(error);
    }
  }
}

module.exports = new UserController();
</code></pre>

<h2 id="defining-routes">Defining Routes</h2>

<p>Now let&#39;s set up our routes in <code>src/routes/userRoutes.js</code>:</p>

<pre><code class="language-javascript">const express = require(&#39;express&#39;);
const router = express.Router();
const UserController = require(&#39;../controllers/userController&#39;);

// GET all users
router.get(&#39;/&#39;, UserController.getAllUsers);

// GET user by ID
router.get(&#39;/:id&#39;, UserController.getUserById);

// POST new user
router.post(&#39;/&#39;, UserController.createUser);

// PUT update user
router.put(&#39;/:id&#39;, UserController.updateUser);

// DELETE user
router.delete(&#39;/:id&#39;, UserController.deleteUser);

module.exports = router;
</code></pre>

<h2 id="testing-the-api">Testing the API</h2>

<p>Let&#39;s test our API with some HTTP requests. You can use tools like Postman, curl, or even a simple fetch in the browser.</p>

<p><img src="https://images.unsplash.com/photo-1581276879432-15e50529f34b?auto=format&amp;fit=crop&amp;w=800&amp;q=80" alt="Testing API with Postman"></p>



<p>Here&#39;s a sample curl command to get all users:</p>

<p><div id="terminal-curl"></div>
</p>

<h2 id="conclusion">Conclusion</h2>

<p>We&#39;ve built a simple RESTful API using Node.js and Express! This example demonstrates:</p>
<ol><li>Setting up an Express server</li>
<li>Creating routes</li>
<li>Implementing controllers</li>
<li>Building a simple data model</li></ol>

<p>In a real-world application, you would want to add:</p>
<ul><li>Database integration (MongoDB, PostgreSQL, etc.)</li>
<li>Authentication and authorization</li>
<li>Input validation</li>
<li>Testing</li>
<li>Documentation</li></ul>

<h2 id="next-steps">Next Steps</h2>

<p>Try extending this API with:</p>
<ul><li>Adding more endpoints</li>
<li>Implementing search functionality</li>
<li>Adding authentication with JWT</li>
<li>Connecting to a real database</li></ul>

<p>Happy coding!</p>


]]></content:encoded>
      <guid>https://logicalbee.in/building-a-restful-api-with-node-js-and-express</guid>
      <pubDate>Sun, 14 Sep 2025 06:55:31 +0000</pubDate>
    </item>
  </channel>
</rss>