Backend

How to Build a REST API with Node.js and Express (Beginner Guide)

Node.jsExpress.jsREST APIBackend

Introduction

Node.js combined with Express.js is one of the most popular stacks for building fast and scalable REST APIs. Express is a lightweight framework that simplifies routing, middleware, and request handling.


Step 1 — Verify Node.js Installation

Make sure Node.js and NPM are installed on your system:

node -v
npm -v

Step 2 — Create a New Project Folder

mkdir node-express-api
cd node-express-api

Step 3 — Initialize NPM Project

npm init -y

Step 4 — Install Express.js

npm install express

Step 5 — Create Entry File

Create a file named index.js:

touch index.js

Add the following code

const express = require("express");
const app = express();

app.use(express.json());

app.get("/", (req, res) => {
  res.json({ message: "API is running successfully" });
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});


Step 6 — Start the Server

node index.js

Open your browser and visit:

http://localhost:3000

Step 7 — Create a Sample API Route

Add this route below the root route:

app.get("/api/users", (req, res) => {
  res.json([
    { id: 1, name: "John Doe" },
    { id: 2, name: "Jane Doe" }
  ]);
});

visit

http://localhost:3000/api/users

Step 8 — Install Nodemon (Optional)

npm install --save-dev nodemon

Update package.json:

"scripts": {
  "dev": "nodemon index.js"
}

Run server in development mode:

npm run dev

Useful Express Commands

| Command | Description | |-----------------------|---------------------------| | node index.js | Start server | | npm run dev | Start server with nodemon | | npm install express | Install Express |


Troubleshooting

If port 3000 is busy:

PORT=3001 node index.js

If nodemon is not recognized, install it globally:

npm install -g nodemon

Conclusion

Express.js makes it easy to build REST APIs with Node.js using clean and minimal code. This setup is ideal for backend services and full-stack applications.


Author

Marquefactory DevOps Team