How to Build a Simple REST API with Node.js and Express.

Building a REST API is a fundamental skill for any web developer. In this guide, I'll walk you through creating a simple REST API using Node.js and Express — a fast and minimal web framework for Node.


Step 1: Create Your Project Folder and Initialize

  • Open your terminal.

  • Create a new folder for your project and move inside it:

mkdir simple-api
cd simple-api
  • Initialize a new Node.js project. This creates a package.json file to manage dependencies:
npm init -y

Step 2: Install Express

Express makes handling HTTP requests straightforward.

  • Install Express in your project by running:
npm install express

Step 3: Create Your Server File

  • Inside your project folder, create a new file called index.js.

  • This file will contain your server code.


Step 4: Write Basic Server Code

Open index.js and add the following code:

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

app.use(express.json()); // Parse JSON request bodies

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
  • This code sets up a basic Express server that listens on port 3000.

Step 5: Add Sample Data

Add a simple list of users inside index.js to work with:

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

Step 6: Create API Endpoints

Add these routes inside index.js after the sample data:

Get all users

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

Get a single 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);
});

Add a new user

app.post('/users', (req, res) => {
  const user = {
    id: users.length + 1,
    name: req.body.name
  };
  users.push(user);
  res.status(201).json(user);
});

Update a user by ID

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 a user by ID

app.delete('/users/:id', (req, res) => {
  users = users.filter(u => u.id !== parseInt(req.params.id));
  res.sendStatus(204);
});

Step 7: Run Your API Server

  • Save your index.js file.

  • Run your server from the terminal:

node index.js
  • You should see:
    Server running on http://localhost:3000

Step 8: Test Your API

Use a tool like Postman or your browser and terminal to test the endpoints:

  • Get all users:
    Visit http://localhost:3000/users in your browser or send a GET request.

  • Get a user by ID:
    GET http://localhost:3000/users/1

  • Add a user:
    Send a POST request to http://localhost:3000/users with JSON body:
    { "name": "Charlie" }

  • Update a user:
    Send a PUT request to http://localhost:3000/users/1 with JSON body:
    { "name": "Alice Updated" }

  • Delete a user:
    Send a DELETE request to http://localhost:3000/users/1


Final Thoughts

Congratulations! You just built a simple REST API using Node.js and Express. From here, you can extend this API by adding a database, authentication, or other features.

0
Subscribe to my newsletter

Read articles from FavourMogbonjubola directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

FavourMogbonjubola
FavourMogbonjubola

I'm a passionate full-stack web developer with a strong foundation in front-end and back-end technologies. I've honed my skills in HTML, CSS, JavaScript, Python, C, and more. I’m driven by a love for problem-solving and innovation, particularly in the field of Artificial Intelligence. I believe in the power of technology to shape a better future, and I’m excited to contribute to projects that push boundaries and create meaningful impact