How to Build a REST API with Node.js: A Step-by-Step Tutorial

Node.js, combined with Express, makes building a REST API fast and lightweight. In this tutorial, you’ll create a simple CRUD API for managing items, covering routes, JSON handling, and testing with a HTTP client.

Prerequisites and Project Setup

Ensure Node.js (v14+) and npm are installed. Create a new project folder and initialize it:

  • mkdir my-rest-api && cd my-rest-api
  • npm init -y
  • Install Express: npm install express

Create a file server.js – this will house your entire API logic.

Article illustration

Writing the Server and Basic Route

Start with a basic Express server and a health-check endpoint. Open server.js and add:

  • const express = require('express'); const app = express();
  • Use express.json() middleware to parse JSON bodies.
  • Define app.get('/api/items', (req, res) => { ... }) that returns a hardcoded array.
  • Listen on port 3000 and log a startup message.

Run the server with node server.js. Visit http://localhost:3000/api/items – you should see an empty JSON array or your sample data.

Implementing CRUD Operations

Now expand your API with Create, Read, Update, and Delete endpoints using an in-memory array for simplicity.

Get All Items and Get Single Item

  • GET /api/items – returns all items.
  • GET /api/items/:id – finds item by ID and returns it, or sends 404 if not found.

Create, Update, and Delete

  • POST /api/items – reads req.body, creates a new item with a unique ID (use a counter), and responds with 201 status.
  • PUT /api/items/:id – updates item fields from req.body, returns updated item or 404.
  • DELETE /api/items/:id – removes item from array, returns 204 No Content or 404.

Test each endpoint using curl, Postman, or any REST client.

Best Practices and Next Steps

To make your API production-ready:

  • Validate input (e.g., check for required fields).
  • Use environment variables (via dotenv) for port and database URLs.
  • Add error handling middleware.
  • Use a real database like MongoDB or PostgreSQL with an ODM/ORM (Mongoose, Sequelize).

You’ve now built a functional REST API with Node.js and Express in just a few steps.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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