A Complete Guide to Build REST API Using Node JS and Express

Learn how to build REST API using Node JS and Express with clear steps, real examples, and best practices. This guide helps you create, test, and scale APIs with simple code and practical tips.

Complete tutorial is here

What Is a REST API and Why It Matters

A way for apps to communicate with each other is a REST API. It employs GET, POST, PUT, and DELETE HTTP methods. The server responds with data when a request is made to a specific URL. Because it is simple to read and work with, the majority of APIs use JSON.

REST API Using Node JS

REST APIs are used every day by you. When you open a weather app or log in to a website, the app sends requests to a server. The server returns the data. Apps remain flexible and quick thanks to this flow. When you use Node JS to build a REST API, you get speed and a big ecosystem.

Why Choose Node Js and Express?

Node Js runs JavaScript on the server. It uses an event driven model. This means it can handle many requests at the same time without slowing down. This works well for apps with many users.

REST API Using Node JS

Express is a simple framework built on Node Js. It helps you create routes, handle requests, and send responses with less code. Many teams use Express because it is easy to learn and quick to set up. When you Build REST API using Node JS and Express, you save time and keep your code clean.

Setting Up Your Development Environment

Start by installing Node Js from the official website. After install, check your version with node -v and npm -v. NPM helps you manage packages.

Create a new folder for your project. Open a terminal and run the following commands

mkdir my-api
cd my-api
npm init -y
npm install express

This creates your project and installs Express. You now have the base ready to Build REST API using Node JS./

Creating Your First Express Server

Create a file named server.js. Add the following code:

const express = require('express');
const app = express();
const PORT = 3000;app.get('/', (req, res) => {
res.send('API is running');<br>});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});

Run your server with:

node server.js

Open your browser and go to http://localhost:3000. You should see the message. This confirms your setup works.

Understanding Routes and HTTP Methods

Routes define how your API responds to requests. Each route has a path and a method. For example:

app.get('/users', (req, res) => {
  res.json({ message: 'Get all users' });
});app.post('/users', (req, res) => {
  res.json({ message: 'Create user' });
});

GET reads data. POST creates data. PUT updates data. DELETE removes data. When you Build REST API using Node JS, use proper methods to keep your API standard and clear.

Handling Requests and Responses

Express gives you req and res objects. You use them to read input and send output.

Example:

app.post('/data', (req, res) => {
  const body = req.body;
  res.json({
    message: 'Data received',
    data: body
  });
});

Add JSON middleware to parse incoming data:

app.use(express.json());

Use status codes for clarity:

res.status(200).json({ success: true });

Working with Middleware

Middleware runs before your route handler. It helps with logging, validation, and more.

Example of custom middleware:

const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};
app.use(logger);

Middleware keeps your app modular. When you Build REST API using Node JS, use middleware to keep logic clean and reusable.

Connecting to a Database

REST API Using Node JS

Install mongoose to connect MongoDB:

npm install mongoose

Connect to your database:

const mongoose = require('mongoose');mongoose.connect('mongodb://127.0.0.1:27017/mydb')
  .then(() => console.log('DB connected'))
  .catch(err => console.log(err));

Create a schema and model:

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});const User = mongoose.model('User', userSchema);

This lets you store and manage data easily.

Building CRUD Operations

Create routes for CRUD actions:

Create:

app.post('/users', async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.json(user);
});

Read:

app.get('/users', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

Update:

app.put('/users/:id', async (req, res) => {
  const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
  res.json(user);
});

Delete:

app.delete('/users/:id', async (req, res) => {
  await User.findByIdAndDelete(req.params.id);
  res.json({ message: 'User deleted' });
});

This is a core pattern when you Build REST API using Node JS.

Validating Data and Handling Errors

Install validator:

npm install express-validator

Example validation:

const { body, validationResult } = require('express-validator');app.post('/users',
  body('email').isEmail(),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    res.send('Valid data');
  }
);

Handle errors with try catch:

app.get('/error', async (req, res) => {
  try {
    throw new Error('Test error');
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

Testing Your API

Use Postman or similar tools. Send requests and check responses.

Postman is a tool you use to test APIs. It helps you send HTTP requests like GET, POST, PUT, and DELETE to your server. You enter a URL, choose a method, and send the request. Postman shows the response, status code, and data in a clear format. You can also add headers, body data, and authentication details. This makes testing fast and simple. Many developers use Postman when they Build REST API using Node JS. It helps you find errors, check responses, and improve your API before you share it with others.

REST API Using Node JS

Example test with fetch:

fetch('http://localhost:3000/users')
  .then(res => res.json())
  .then(data => console.log(data));
REST API Using Node JS

Automated testing with Jest:

Jest is a testing tool for JavaScript. You use it to check if your code works as expected. It runs tests and shows results in a simple way. You write small test cases and compare expected output with actual output. Jest supports unit testing, async testing, and mocking. This helps you test each part of your API. Many developers use Jest when they Build REST API using Node JS. It helps catch bugs early and keeps your code stable. You can run tests with one command and see clear results in your terminal

npm install jest

Simple test:

test('sample test', () => {
  expect(1 + 1).toBe(2);
});

Testing ensures your API works after updates.

Securing Your API

Install JWT:

npm install jsonwebtoken

Create token:

const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: 1 }, 'secret', { expiresIn: '1h' });

Verify token:

jwt.verify(token, 'secret', (err, decoded) => {
 if (err) return res.status(401).send('Unauthorized');
});

Use HTTPS and store secrets in .env files:

npm install dotenv
require('dotenv').config();
console.log(process.env.SECRET_KEY);

Organizing Your Project Structure

A clean structure helps manage large apps.

Example structure:

/project
 /routes
 /controllers
 /models
 /middleware
server.js

Keep logic in controllers:

exports.getUsers = (req, res) => {
  res.send('Users list');
};

Import in routes:

const express = require('express');
const router = express.Router();
const { getUsers } = require('../controllers/userController');router.get('/users', getUsers);module.exports = router;

Deploying Your API

Prepare your app for production. Add a start script:

"scripts": {
  "start": "node server.js"
}

Use PM2:

npm install -g pm2
pm2 start server.js

Deploy to platforms like Render or DigitalOcean. After deploy, test all routes.

Best Practices for Long Term Success

Use versioning:

app.use('/api/v1', routes);

Log requests and errors. Keep dependencies updated:

npm update

Use environment configs for different stages. When you Build REST API using Node JS, these steps help maintain quality.

Final Thoughts

Building APIs with Node Js and Express gives you full control over your backend. You can create endpoints, manage data, and handle users with simple code. This makes it easier to build apps that work fast and handle many requests.

Start with a small project and learn the basics. Then add more features step by step. With regular practice, you improve your skills and write better code. Over time, you can build fast and scalable APIs for real world use. When you Build REST API using Node JS, you gain useful skills for modern web development.

Leave a Comment