01 Introduction To Nodejs Rest Apis
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
- 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.
- Not handling promise rejections — Unhandled promise rejections crash Node.js processes. Use try/catch in async functions and process.on('unhandledRejection').
- Forgetting error handling in Express routes — Wrap async route handlers in try/catch or use an express-async-errors package to catch rejected promises.
- 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.
- Not using environment variables — Hard-coding configuration like database passwords and API keys creates security risks and deployment issues.
Practice Questions
- What is the event loop and why is it important for REST APIs?
- Why does Node.js handle concurrent connections efficiently?
- What happens if you block the event loop with a synchronous operation?
- How do you handle errors in async Express route handlers?
- 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
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