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

Building a REST API with Node.js is one of the most sought-after skills for backend development. In this tutorial, you’ll create a simple, functional API using Express, the de facto framework for Node.js.

First, initialize your project folder by running npm init -y, then install Express with npm install express.

Article illustration

Set Up the Express Server

Create a file named server.js. Import Express, add the express.json() middleware for parsing JSON bodies, and start the server on port 3000.

const express = require('express');
const app = express();
app.use(express.json());
app.listen(3000, () => console.log('API running'));

Design the Routes

A REST API relies on CRUD operations. Use a simple in-memory array as your data store and define these endpoints:

  • GET /items — fetch all items
  • POST /items — create a new item
  • PUT /items/:id — update an existing item
  • DELETE /items/:id — remove an item

Each route handler receives the request and returns a JSON response.

Test Your API

Run node server.js and test with Postman or curl. Send JSON payloads with the Content-Type: application/json header, then verify the status codes and response bodies.

Conclusion

Your REST API is ready. Next, connect a database like MongoDB, add input validation, and deploy it to the cloud.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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