How to Build a REST API with Node.js and Express

Node.js is an excellent choice for building fast, scalable APIs, and Express makes the process incredibly straightforward. This tutorial walks through creating a simple REST API from scratch, covering setup, routes, and testing.

Make sure you have Node.js and npm installed. You can test the endpoints using a browser, Postman, or curl.

Article illustration

1. Initialize the Project

Create a project folder and run npm init -y to generate a package.json file. Then install Express with npm i express.

2. Create the Server

Create an index.js file and add the following code to start a server on port 3000.

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

3. Add API Routes

Define endpoints using HTTP methods. Here’s a simple GET route that returns JSON.

app.get('/api', (req, res) => {
  res.json({ message: 'Hello World' });
});

Use app.post(), app.put(), and app.delete() for other operations.

4. Test the API

Run node index.js and visit http://localhost:3000/api. You should see the JSON response. Use Postman to send POST, PUT, and DELETE requests to test further.

There you have it — a fully functional API built with Node.js and Express. From here, you can expand by adding a database, implementing authentication, and organizing routes with Express Router to build production-ready services.

sarah antaboga
Author: sarah antaboga

Leave a Reply

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