Build a rest api with node.js in 15 minutes

Build a rest api with node.js in 15 minutes

To build a REST API with Node.js is a fundamental skill for any backend developer. REST, which stands for Representational State Transfer, is a set of constraints that makes your web services scalable and easy to maintain. By utilizing Node.js, you gain the benefit of a non-blocking, event-driven architecture that handles concurrent requests with high efficiency. According to the Stack Overflow Developer Survey (2023), Node.js remains the most commonly used web technology, making it a reliable choice for your infrastructure. In this tutorial, you will set up a lightweight server using the Express framework to manage data resources through standard HTTP methods. You will gain hands-on experience in routing, request handling, and JSON response formatting.

Prerequisites

rest api with node.js
Photo by Elina Sazonova / Pexels
  • Node.js version 18.0.0 or higher installed on your machine.
  • NPM (Node Package Manager) which comes bundled with Node.js.
  • A code editor like Visual Studio Code.
  • Basic familiarity with JavaScript and terminal commands.

Key takeaway: Having the right environment ensures your dependencies install without version conflicts.

Setup

First, initialize your project to create a package.json file, which tracks your project’s dependencies and configuration. Open your terminal in your project folder and run the following commands to set up the foundation:

mkdir node-api-demo
cd node-api-demo
npm init -y
npm install express

In practice, I always use a tool like nodemon to automatically restart the server when I save files. You can install it with npm install –save-dev nodemon. This saves significant time during active development cycles.

Key takeaway: Clean initialization provides a structured baseline for your backend project.

Creating the server

Now, create a file named index.js in your root directory. This will serve as the entry point for your application. We will define a simple Express app that listens on port 3000 and exposes a welcome route. Copy this code into your file:

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

app.get('/', (req, res) => {
  res.json({ message: 'Welcome to the REST API with Node.js' });
});

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});

Once saved, start your server by running node index.js in your terminal. You should see the message confirming the server is active. This confirms that Express is properly handling requests.

Key takeaway: A minimal server instance is the necessary starting point for adding complex endpoints.

Implementing crud endpoints

A real API needs to manage data. We will add an in-memory array to store items and implement CRUD (Create, Read, Update, Delete) operations. Replace your existing index.js content with this version:

let items = [{ id: 1, name: 'Sample Item' }];

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

app.post('/items', (req, res) => {
  const newItem = { id: items.length + 1, ...req.body };
  items.push(newItem);
  res.status(201).json(newItem);
});

app.put('/items/:id', (req, res) => {
  const index = items.findIndex(i => i.id === parseInt(req.params.id));
  items[index] = { ...items[index], ...req.body };
  res.json(items[index]);
});

app.delete('/items/:id', (req, res) => {
  items = items.filter(i => i.id !== parseInt(req.params.id));
  res.status(204).send();
});

A common mistake here is forgetting the express.json() middleware, which allows Express to parse the incoming request body as JSON. Without it, your POST requests will return undefined. Furthermore, according to the Web Almanac (2022), properly typed JSON responses are critical for maintaining API interoperability between different frontend frameworks.

Key takeaway: Implementing standard HTTP verbs allows your API to communicate state changes effectively.

Testing it

Testing your backend development work is straightforward using a tool like Postman or a simple curl command. If you prefer the terminal, try creating a new item with a POST request:

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

You should see the JSON response reflecting the new object. Verify the state by hitting the /items endpoint with a GET request. What most guides miss is that checking your status codes (like 201 for Created or 204 for No Content) is just as important as checking the body of the response.

Key takeaway: Manual validation via CLI tools confirms your route logic handles data correctly.

Common errors

Address already in use

If you see an EADDRINUSE error, it means another process is already holding port 3000. Use lsof -i :3000 to find the process ID and kill it before restarting your server.

404 Not Found

Double-check your route parameters. If your route is defined as /items/:id but you are hitting /items/undefined, ensure your client-side code is passing the ID correctly.

Key takeaway: Most errors arise from port conflicts or malformed request URLs.

Congratulations, you have successfully deployed a functional REST API with Node.js. You have learned how to structure an Express app, process incoming JSON payloads, and handle CRUD operations. This setup is the bedrock of modern microservices. In practice, as your application grows, you will want to move logic into controllers and add a database layer like MongoDB or PostgreSQL to persist your data. The next step is to explore environment variables using the dotenv package to keep your credentials secure. From there, consider adding validation libraries like Joi or Zod to ensure the data entering your system meets your strict requirements. Every professional backend developer started exactly where you are today. Keep building, iterate on your routes, and focus on clean, predictable error handling as you scale your projects toward production environments.

Cover image by: Gagareen / Pexels

Leave a Comment

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

Scroll to Top