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

Node.js, combined with Express, is a powerful and lightweight choice for building REST APIs. This tutorial walks you through creating a basic API with standard CRUD operations, perfect for beginners or anyone needing a quick, scalable backend.

Start by initializing a new project: run npm init -y in your terminal, then install Express with npm install express. Create a file named index.js for your server.

Article illustration

1. Set Up Your Express Server

In index.js, require Express and create an app instance. Define a port and start listening:

  • const express = require('express');
  • const app = express();
  • app.listen(3000, () => console.log('API running on port 3000'));

2. Define Routes and HTTP Methods

Use Express route handlers for CRUD operations. For a simple items resource:

  • GET /api/items – return array of items.
  • POST /api/items – add new item from request body.
  • PUT /api/items/:id – update existing item.
  • DELETE /api/items/:id – remove item.

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

3. Add Middleware

Use built-in express.json() to parse JSON request bodies. Add error-handling middleware at the end:

app.use(express.json());
app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });

4. Test Your API

Run node index.js and test endpoints with Postman or curl. For example:

  • curl http://localhost:3000/api/items
  • curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' http://localhost:3000/api/items

Building a REST API with Node.js is straightforward. Start with the basics, then add databases like MongoDB, authentication, and validation. The key is to keep routes clean and middleware modular. Happy coding!

sarah antaboga
Author: sarah antaboga

Leave a Reply

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