How to Create a RESTful API with Node.js: A Step-by-Step Guide

RESTful APIs are essential for modern web apps, and Node.js makes building them efficient and fast. In this guide, we’ll create a simple RESTful API with Express, covering the core CRUD operations.

Before you start, make sure Node.js and npm are installed on your machine. You can verify this by running node -v and npm -v.

Article illustration

Step 1: Set Up the Project

Create a new directory and run these commands:

  • mkdir my-api && cd my-api
  • npm init -y
  • npm install express

This creates a package.json file and installs Express, the most popular web framework for Node.js.

Step 2: Build the Server

Create an index.js file and set up a basic Express server:

const express = require('express');
const app = express();
app.use(express.json());
app.listen(3000);

Step 3: Define CRUD Routes

Use Express methods to handle HTTP requests. Here are the endpoints we’ll implement:

  • GET /api/items – Fetch all items
  • POST /api/items – Create a new item
  • PUT /api/items/:id – Update an item
  • DELETE /api/items/:id – Remove an item

Step 4: Test the API

Start the server with node index.js and test with curl or Postman:

curl http://localhost:3000/api/items

Conclusion

You’ve now built a working RESTful API with Node.js. Add a database, validation, and middleware to make it production-ready.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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