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

Node.js, combined with Express, provides a lightweight and efficient way to build REST APIs. This tutorial walks you through creating a simple API for managing a list of items, covering the essential steps from setup to testing.

Before starting, ensure you have Node.js and npm installed. Create a new project folder and run npm init -y to generate a package.json.

Article illustration

1. Install Dependencies

Install Express for the server and body-parser for parsing JSON requests. Optionally install nodemon for automatic restarts.

  • npm install express body-parser
  • npm install --save-dev nodemon

2. Create the Server

Create an index.js file. Import Express, set up the app to use JSON parsing, and start the server on a port (e.g., 3000).

  • Set up const express = require('express'); const app = express();
  • Use app.use(bodyParser.json());
  • Add app.listen(3000, () => console.log('Server running'));

3. Define API Routes

Build CRUD routes for a sample resource (books). Use an in-memory array for simplicity.

  • GET /books – return all books.
  • POST /books – add a new book (parse body).
  • GET /books/:id – get a single book.
  • PUT /books/:id – update a book.
  • DELETE /books/:id – remove a book.

4. Test Your API

Run the server with node index.js (or nodemon). Use Postman or curl to send requests to http://localhost:3000/books.

You now have a working REST API built with Node.js. Expand it by adding a database (MongoDB with Mongoose) or authentication. Experiment with middleware and error handling to make it production-ready.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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