Building a Simple REST API with Node.js and Express

Tobechi DuruTobechi Duru
2 min read

Introduction

A REST API is one of the most common back-end solutions for modern applications. Whether you are building a mobile app, a web service, or a microservice for a larger system, knowing how to create a simple REST API is essential.

In this guide, we will create a small but functional REST API using Node.js and Express. You will learn the basics of routing, handling JSON data, and testing endpoints.


Project Structure

Here’s the folder layout we will use:

pgsqlCopyEditmy-api/
│   package.json
│   server.js
└── routes/
    └── tasks.js

Step 1: Initialize the Project

Run the following commands in your terminal:

bashCopyEditmkdir my-api && cd my-api
npm init -y
npm install express

Step 2: Create the Server

server.js

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

app.use(express.json());

const tasksRouter = require('./routes/tasks');
app.use('/tasks', tasksRouter);

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

Step 3: Add the Routes

routes/tasks.js

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

let tasks = [
  { id: 1, title: 'Learn Node.js' },
  { id: 2, title: 'Build a REST API' }
];

router.get('/', (req, res) => {
  res.json(tasks);
});

router.post('/', (req, res) => {
  const newTask = { id: tasks.length + 1, title: req.body.title };
  tasks.push(newTask);
  res.status(201).json(newTask);
});

router.delete('/:id', (req, res) => {
  tasks = tasks.filter(task => task.id != req.params.id);
  res.json({ message: 'Task deleted' });
});

module.exports = router;

Step 4: Test the API

You can use Postman or curl to test:

  • GET /tasks → Get all tasks

  • POST /tasks with { "title": "Your Task" } → Add a new task

  • DELETE /tasks/:id → Remove a task


Why This Matters

This small project covers real-world fundamentals:

  • Understanding Express middleware

  • Organizing routes in a modular way

  • Using JSON for communication

  • Following REST principles

These skills apply directly to production-grade systems and can be expanded into more complex applications with authentication, databases, and deployment.


Conclusion

This simple REST API is a stepping stone toward mastering back-end development. You can extend it by adding a database like MongoDB, integrating authentication, or deploying it to a cloud platform.

If you try this out, share your results and improvements in the comments. I’m curious to see how you take it further.

0
Subscribe to my newsletter

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

Written by

Tobechi Duru
Tobechi Duru

Software Engineer, MERN-Stack Developer