What Is a REST API and Why Does It Matter?

A REST (Representational State Transfer) API is the backbone of modern web applications. It allows your front-end, mobile apps, and third-party services to communicate with your server using standard HTTP methods. If you're building anything beyond a static website, knowing how to create a REST API is an essential skill.

In this tutorial, we'll walk through building a fully functional REST API using Node.js and Express — one of the most popular server-side JavaScript frameworks.

Prerequisites

  • Node.js (v18 or later) installed on your machine
  • Basic understanding of JavaScript
  • A code editor (VS Code recommended)
  • Postman or a similar tool for testing API endpoints

Step 1: Initialize Your Project

Start by creating a new project directory and initializing a Node.js project:

mkdir my-rest-api
cd my-rest-api
npm init -y

Next, install Express and a few useful middleware packages:

npm install express cors dotenv
npm install --save-dev nodemon

Step 2: Set Up Your Express Server

Create an index.js file at the root of your project. This is your server's entry point:

const express = require('express');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());

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

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

Step 3: Create Your Routes

Organize your API into route modules. For a simple users resource, create a routes/users.js file:

const express = require('express');
const router = express.Router();

let users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];

router.get('/', (req, res) => res.json(users));
router.get('/:id', (req, res) => {
  const user = users.find(u => u.id === parseInt(req.params.id));
  user ? res.json(user) : res.status(404).json({ error: 'User not found' });
});
router.post('/', (req, res) => {
  const newUser = { id: users.length + 1, ...req.body };
  users.push(newUser);
  res.status(201).json(newUser);
});

module.exports = router;

Then register the route in your index.js:

const usersRouter = require('./routes/users');
app.use('/api/users', usersRouter);

Step 4: Handle Errors Gracefully

Always add a global error handler to catch unexpected issues:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something went wrong!' });
});

Step 5: Test Your API

Run your server with npx nodemon index.js and use Postman (or curl) to test each endpoint:

  • GET /api/users — returns all users
  • GET /api/users/1 — returns a single user
  • POST /api/users — creates a new user

Best Practices to Follow

  1. Always validate incoming request data before processing.
  2. Use environment variables for sensitive config (never hardcode secrets).
  3. Version your API (e.g., /api/v1/users) from the start.
  4. Return meaningful HTTP status codes (200, 201, 400, 404, 500).
  5. Document your endpoints using tools like Swagger or Postman Collections.

Next Steps

Once your basic API is running, consider connecting it to a database (MongoDB with Mongoose or PostgreSQL with Prisma), adding authentication with JWT, and deploying to a platform like Railway, Render, or AWS.