How to Build a RESTful API with Express: A Step-by-Step Guide

Express is the most popular framework for building RESTful APIs with Node.js. It is lightweight, fast, and offers a clean way to handle HTTP requests. In this tutorial, you’ll learn how to build a practical API from scratch, covering routing, CRUD operations, and middleware.

Before we start, ensure you have Node.js and npm installed on your machine. Basic knowledge of JavaScript and REST conventions (GET, POST, PUT, DELETE) will help you follow along smoothly.

Article illustration

1. Project Setup

Create a new directory and initialize your project with the following commands:

  • npm init -y – creates a package.json file.
  • npm install express – installs the Express framework.
  • npm install --save-dev nodemon – auto-restarts your server during development.

2. Create the Server and Initial Route

Create an index.js file with a basic Express server:

const express = require('express');
const app = express();
app.use(express.json()); // Parse JSON bodies

app.get('/', (req, res) => res.send('API is running'));
app.listen(3000, () => console.log('Server on port 3000'));

3. Implement CRUD Operations

Create an in-memory array as your data store, then define the API endpoints:

let items = [{ id: 1, name: 'Apple' }];

// GET all items
app.get('/api/items', (req, res) => res.json(items));

// GET a single item by ID
app.get('/api/items/:id', (req, res) => {
  const item = items.find(i => i.id === parseInt(req.params.id));
  item ? res.json(item) : res.status(404).send('Not found');
});

// POST a new item
app.post('/api/items', (req, res) => {
  const newItem = { id: items.length + 1, name: req.body.name };
  items.push(newItem);
  res.status(201).json(newItem);
});

// PUT: update an existing item
app.put('/api/items/:id', (req, res) => {
  const item = items.find(i => i.id === parseInt(req.params.id));
  if (!item) return res.status(404).send('Not found');
  item.name = req.body.name;
  res.json(item);
});

// DELETE an item
app.delete('/api/items/:id', (req, res) => {
  items = items.filter(i => i.id !== parseInt(req.params.id));
  res.status(204).send();
});

4. Test Your API

Run npm start (with nodemon) and test the endpoints using Postman, curl, or your browser. Use express.json() middleware to handle request bodies and consider adding morgan for request logging.

Conclusion: You’ve built a functional RESTful API with Express in just a few steps. From here, you can connect a real database, add authentication, and structure your routes with Express Router for larger projects.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *