Huzi Blogs
Blog
Blog
Disclaimer & Data Privacy Policy
Project by huzi.pk

© 2026 blogs.huzi.pk. All Rights Reserved.

    Back to all posts
    Programming

    Building a REST API with Node.js and Express

    By Huzi

    What is a REST API?

    A REST (Representational State Transfer) API is an architectural style for designing networked applications. It relies on a stateless, client-server communication protocol—almost always HTTP. REST APIs are the backbone of modern web services, allowing different applications to communicate with each other over the internet.

    Why Node.js and Express?

    • Node.js is a JavaScript runtime built on Chrome's V8 engine. It allows you to run JavaScript on the server, making it perfect for building fast and scalable network applications.
    • Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building APIs by providing tools for routing, middleware, and handling HTTP requests and responses.

    Setting Up Your Project

    First, make sure you have Node.js and npm (Node Package Manager) installed.

    1. Initialize your project:

      mkdir my-api
      cd my-api
      npm init -y
      
    2. Install Express:

      npm install express
      

    Creating Your First Server

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

    const express = require('express');
    const app = express();
    const port = 3000;
    
    // Middleware to parse JSON bodies
    app.use(express.json());
    
    app.get('/', (req, res) => {
      res.send('Hello, World!');
    });
    
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
    

    Run your server with node index.js. You can now visit http://localhost:3000 in your browser and see "Hello, World!".

    Building API Endpoints (Routing)

    A REST API is defined by its endpoints. Let's create a simple in-memory "database" and build CRUD (Create, Read, Update, Delete) endpoints for a collection of users.

    // ... (keep the initial setup code)
    
    let users = [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ];
    
    // GET all users
    app.get('/api/users', (req, res) => {
      res.json(users);
    });
    
    // GET a single user by ID
    app.get('/api/users/:id', (req, res) => {
      const user = users.find(u => u.id === parseInt(req.params.id));
      if (!user) return res.status(404).send('User not found.');
      res.json(user);
    });
    
    // POST a new user
    app.post('/api/users', (req, res) => {
      if (!req.body.name || req.body.name.length < 3) {
        return res.status(400).send('Name is required and should be minimum 3 characters.');
      }
      const newUser = {
        id: users.length + 1,
        name: req.body.name
      };
      users.push(newUser);
      res.status(201).json(newUser);
    });
    
    // PUT (update) a user
    app.put('/api/users/:id', (req, res) => {
      const user = users.find(u => u.id === parseInt(req.params.id));
      if (!user) return res.status(404).send('User not found.');
    
      user.name = req.body.name;
      res.json(user);
    });
    
    // DELETE a user
    app.delete('/api/users/:id', (req, res) => {
      const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
      if (userIndex === -1) return res.status(404).send('User not found.');
    
      const deletedUser = users.splice(userIndex, 1);
      res.json(deletedUser);
    });
    
    
    // ... (keep the app.listen code)
    

    Next Steps: Connecting to a Database

    While an in-memory array is great for learning, a real-world application needs a persistent database like MongoDB or PostgreSQL. You would use a library like Mongoose (for MongoDB) or Sequelize (for SQL databases) to connect your Express app to the database and replace the users array with database queries.

    Conclusion

    You've successfully built a basic REST API with Node.js and Express! You've learned how to set up a server, create routes for different HTTP methods, and perform CRUD operations. This is a fundamental skill for any back-end or full-stack developer. From here, you can explore middleware for authentication, error handling, and connecting to a real database.

    Advertisements


    You Might Also Like

    Pair Silicone Kitchen Gloves – Built-in Scrubbers, 450°F Heat-Safe, 2 Count

    Pair Silicone Kitchen Gloves – Built-in Scrubbers, 450°F Heat-Safe, 2 Count

    PKR 1100

    Elegant Heavy Embroidered Organza Suit | Printed Organza Jacquard Dupatta

    Elegant Heavy Embroidered Organza Suit | Printed Organza Jacquard Dupatta

    PKR 5900

    All-Over Print Embroidered Lawn Dress 3-Pc | Printed Chiffon Dupatta

    All-Over Print Embroidered Lawn Dress 3-Pc | Printed Chiffon Dupatta

    PKR 4600

    Heavy Embroidered Lawn 3-Pc Suit | Digital Print Diamond Dupatta (Fancy Wear Pakistan)

    Heavy Embroidered Lawn 3-Pc Suit | Digital Print Diamond Dupatta (Fancy Wear Pakistan)

    PKR 4550

    Trendy Embroidered & Printed Lawn 3-Piece Suit with Printed Chiffon Dupatta

    Trendy Embroidered & Printed Lawn 3-Piece Suit with Printed Chiffon Dupatta

    PKR 4200

    Advertisements


    Related Posts

    Programming
    C# Essential Guide to Modern Programming Techniques
    C# is a versatile programming language from Microsoft, running on the .NET platform. It supports multiple programming styles and is used to build a wide range of applications, including web, desktop, mobile, and games. It is known for its clear syntax and strong typing.

    By Huzi

    Read More
    Programming
    The Ultimate Beginner's Guide to Building a Website with Cloudflare Pages
    This guide provides a comprehensive walkthrough for deploying a modern website on Cloudflare Pages, covering everything from Git setup and local development to serverless functions, security, and monitoring.

    By Huzi

    Read More
    Programming
    Understanding HTML5 and Its Powerful Features
    HTML5 is the latest evolution of the standard that defines HTML. It introduced a host of new semantic elements, multimedia tags, and APIs that are the foundation of the modern web.

    By Huzi

    Read More
    Digital Marketing
    The Global Rise of Personal Branding: How to Build Your Own Identity in 2025
    In today's digital world, your name is your brand. This post explores why personal branding is essential in 2025 and how you can build your own identity online.

    By Huzi

    Read More
    AI
    Unlock Your Day: How AI Tools Automate Routine Tasks in 2025
    AI has evolved into an indispensable architect of daily productivity, transforming hours of manual effort into streamlined, automated processes. Discover the essential AI tools that are reshaping our routines.

    By Huzi

    Read More
    Education
    Best Apps for Remote Learning in 2025
    An evergreen listicle of 10 tried-and-tested apps that dominate remote learning. Includes features, pros/cons, and use-cases.

    By Huzi

    Read More