Build Your First REST API with Node.js and Express

Node.js and Express make backend development fast, simple, and scalable.

REST APIs are widely used for communication between frontend and backend applications.

In this tutorial, you will learn how to build a basic REST API step by step.

By the end, you will have a working API running on your local machine.

Concept Overview

A REST API allows applications to exchange data using HTTP methods like GET, POST, PUT, and DELETE.

Express is a lightweight Node.js framework used to create servers and APIs quickly.

Prerequisites

Node.js installed on your system.

Basic knowledge of JavaScript.

A code editor like VS Code.

Step 1: Create Project Folder

BASH
mkdir my-api
cd my-api

Step 2: Initialize Node.js Project

BASH
npm init -y

Step 3: Install Express

BASH
npm install express

Step 4: Create Server File

BASH
touch server.js

Step 5: Add API Code

JavaScript
const express = require('express');
const app = express();

app.use(express.json());

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

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

app.post('/users', (req, res) => {
  const user = req.body;
  res.json({
    message: 'User added successfully',
    user
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Step 6: Run the Server

BASH
node server.js

Output

TEXT
Server running on port 3000

Test the API

Open your browser and visit:

TEXT
http://localhost:3000/

To test the users endpoint:

TEXT
http://localhost:3000/users

Detailed Explanation

The express() function creates a web application.

The app.get() method handles GET requests.

The app.post() method handles POST requests.

The app.listen() method starts the server on a specific port.

Example Walkthrough

When you visit '/users', the API returns a JSON array of users.

When you send a POST request to '/users', the API accepts and returns the new user data.

Applications

Building backend services for websites and mobile apps.

Creating APIs for frontend frameworks like React or Vue.

Developing scalable web applications.

Advantages of Express APIs

Simple and lightweight framework.

Fast development process.

Large community and ecosystem.

Easy integration with databases.

Limitations

Requires additional packages for advanced features.

Manual structure setup compared to full frameworks.

Improvements You Can Make

Connect MongoDB or MySQL database.

Add authentication using JWT.

Use environment variables with dotenv.

Implement error handling middleware.

Node.js and Express are excellent tools for building modern backend applications and APIs.