Skip to content

01 Introduction To Nodejs Rest Apis

DodaTech 3 min read

title: Introduction to Building REST APIs with Node.js weight: 11 date: 2026-06-28 lastmod: 2026-06-28 description: Learn why Node.js is ideal for building REST APIs — non-blocking I/O, vast ecosystem, single language for frontend and backend, and JavaScript tooling. tags: [api-development, nodejs]


Node.js is a JavaScript runtime built on Chrome's V8 engine that uses non-blocking, event-driven I/O to build scalable REST APIs, making it one of the most popular choices for backend web development.

```mermaid
flowchart TD
  A[Node.js API] --> B[Event Loop]
  B --> C[Non-blocking I/O]
  C --> D[Database]
  C --> E[File System]
  C --> F[External APIs]
  A --> G[Express / Koa]
  G --> H[Middleware Stack]
  H --> I[Request -> Response]
  style A fill:#e1f5fe
  style G fill:#c8e6c9

Node.js excels at building REST APIs because it handles thousands of concurrent connections with a single thread using its event loop. The npm ecosystem provides hundreds of thousands of packages for routing, validation, authentication, database integration, and testing.

Think of Node.js's event loop like a restaurant waiter. Instead of hiring a new waiter for every customer (thread-per-request), one waiter takes orders (events), sends them to the kitchen (I/O), and serves food when ready (callback). This works efficiently even with many customers.

Example: Hello World HTTP Server

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/api/hello' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello, API World!' }));
  } else {
    res.writeHead(404);
    res.end(JSON.stringify({ error: 'Not found' }));
  }
});

server.listen(3000, () => {
  console.log('API server running on http://localhost:3000');
});

Expected output:

API server running on http://localhost:3000

Example: Testing the API

$ curl http://localhost:3000/api/hello
{"message":"Hello, API World!"}

$ curl http://localhost:3000/not-found
{"error":"Not found"}

Example: Using async/await for Database Queries

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

app.get('/api/users/:id', async (req, res) => {
  try {
    const user = await database.findUserById(req.params.id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
  } catch (error) {
    console.error('Database error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

Common Mistakes

  1. Blocking the event loop — Synchronous operations like JSON.parse on large payloads or fs.readFileSync block the event loop and degrade performance for all users.
  2. Not handling promise rejections — Unhandled promise rejections crash Node.js processes. Use try/catch in async functions and process.on('unhandledRejection').
  3. Forgetting error handling in Express routes — Wrap async route handlers in try/catch or use an express-async-errors package to catch rejected promises.
  4. Running Node.js as root — Running Node.js as root is a security risk. Use a non-root user and bind to ports above 1024 with a reverse proxy.
  5. Not using environment variables — Hard-coding configuration like database passwords and API keys creates security risks and deployment issues.

Practice Questions

  1. What is the event loop and why is it important for REST APIs?
  2. Why does Node.js handle concurrent connections efficiently?
  3. What happens if you block the event loop with a synchronous operation?
  4. How do you handle errors in async Express route handlers?
  5. Challenge: Build a minimal HTTP server in Node.js without frameworks that handles GET, POST, PUT, and DELETE for a /tasks resource. Store tasks in memory. Test with curl.

FAQ

Is Node.js good for CPU-intensive APIs?

No, Node.js is optimized for I/O-bound operations. For CPU-heavy tasks, use worker threads or offload to a separate microservice written in a language like Python or Go.

Should I use CommonJS or ES modules?

ES modules (import/export) are the modern standard. CommonJS (require) is still widely used. New projects should use ES modules with type: module in package.json.

What is the difference between Express and Koa?

Express is more mature with a larger ecosystem. Koa uses async/await natively and has a lighter core. Both are excellent choices for building REST APIs.

Do I need TypeScript for Node.js APIs?

TypeScript is optional but recommended for larger projects. It provides type safety, better IDE support, and catches bugs at compile time.

What is the best way to handle environment variables?

Use a .env file with the dotenv package for development. In production, use your platform's environment variable system (Docker, Kubernetes, Heroku).

Mini Project

Create a basic Node.js REST API using only the built-in http module. The API should manage a list of books with CRUD operations. Store books in memory. Test each endpoint with curl commands and verify the responses.

What's Next

Now learn project setup with Express in the next lesson on Building REST APIs with Node.js.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro