Node.js  

Getting Started with REST APIs using Node.js and Express

๐Ÿ“ Project Setup

  1. Install Node.js from https://nodejs.org
  2. Create a new folder for your project.
mkdir rest-api-demo
cd rest-api-demo
npm init -y
npm install express

๐Ÿงฑ Create a Basic Server

Create a file called index.js.

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.send('Welcome to the REST API!');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

Run the server.

node index.js

Visit http://localhost:3000/ and you’ll see a welcome message.

๐Ÿ“ Building CRUD APIs

Let’s build a simple API to manage a list of users.

let users = [
  { id: 1, name: "Altaf" },
  { id: 2, name: "Sarah" }
];

// GET all users
app.get('/users', (req, res) => {
  res.json(users);
});

// GET user by ID
app.get('/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 create new user
app.post('/users', (req, res) => {
  const newUser = {
    id: users.length + 1,
    name: req.body.name
  };
  users.push(newUser);
  res.status(201).json(newUser);
});

// PUT update user
app.put('/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 user
app.delete('/users/:id', (req, res) => {
  users = users.filter(u => u.id !== parseInt(req.params.id));
  res.send('User deleted');
});

๐Ÿงช Testing the API

Use Postman to test the endpoints.

  • GET /users
  • POST /users with body { "name": "New User" }
  • PUT /users/1 with body { "name": "Updated Name" }
  • DELETE /users/2

โœ”๏ธ Summary

In this article, we created a simple REST API using Node.js and Express. This tutorial covered.

  • Setting up a server
  • Creating CRUD endpoints
  • Testing APIs with Postman

With this knowledge, you're now ready to explore more advanced topics, such as

  • Middleware
  • Database integration (MongoDB, PostgreSQL)
  • Authentication (JWT)

๐Ÿ‘จ‍๐Ÿซ About the Author

Mohammed Altaf is a Computer Science Engineering student with a passion for full-stack development. He works with MERN stack projects and loves exploring backend technologies.

๐Ÿ” Author's Copyright Declaration

I, Mohammed Altaf, hereby declare that this article is original, does not contain copied code or content, and all images/code are created by me. I understand and accept the responsibilities outlined in the publishing agreement.