š§ What is a Node.js API?
A Node.js API is a backend service built using Node.js that allows client applications (like web frontends or mobile apps) to send and receive data using HTTP requests ā typically in JSON format.
ā Node.js APIs are lightweight, fast, and perfect for modern web apps.
š Why Use Node.js to Build APIs?
Advantage | Benefit |
---|---|
š§µ Asynchronous & Non-blocking | Handles multiple requests efficiently |
š JavaScript Everywhere | Use the same language for frontend & backend |
š¦ NPM Ecosystem | Tons of packages for routing, DBs, auth, etc. |
ā” Fast & Scalable | Ideal for REST APIs, real-time apps, microservices |
Ā
š§± Basic Node.js REST API (with Express)
1. š¹ Install Node.js & Create Project
bash
mkdir my-api
cd my-api
npm init -y
npm install express
2. š¹ Create index.js
js
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to parse JSON
app.use(express.json());
// Routes
app.get('/', (req, res) => {
res.send('Hello, API!');
});
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'Anil' }, { id: 2, name: 'Sara' }]);
});
app.post('/api/users', (req, res) => {
const user = req.body;
// Save to DB logic goes here
res.status(201).json({ message: 'User created', user });
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
š§Ŗ Test the API
Use Postman, curl, or JavaScript (fetch/Axios) to test:
bash
curl http://localhost:3000/api/users
š Common Features in a Node.js API
Feature | How |
---|---|
Routing | express.Router() |
Validation | joi , express-validator |
Authentication | jsonwebtoken (JWT), passport.js |
Database | mongoose (MongoDB), pg (PostgreSQL), prisma |
CORS | cors middleware |
Error Handling | Centralized error middleware |
Environment Configs | dotenv for .env files |
Ā
š§ REST vs GraphQL API with Node.js
Type | Description | Tools |
---|---|---|
REST | One endpoint per resource | Express.js, Fastify |
GraphQL | Single endpoint, flexible queries | Apollo Server, GraphQL.js |
Ā
š¦ Popular Node.js API Frameworks
Framework | Best For |
---|---|
Express.js | Simple, flexible REST APIs |
Fastify | Performance-optimized APIs |
NestJS | Scalable, TypeScript-first enterprise APIs |
Hapi.js | Enterprise-grade APIs with built-in features |
Ā
š Example: JWT Authentication in Node.js
bash
npm install jsonwebtoken
js
const jwt = require('jsonwebtoken');
const secret = 'mysecret';
// Generate token
const token = jwt.sign({ userId: 1 }, secret, { expiresIn: '1h' });
// Verify token
jwt.verify(token, secret, (err, decoded) => {
if (err) return console.log('Invalid Token');
console.log(decoded); // { userId: 1, iat: ..., exp: ... }
});
ā When to Use Node.js for API Development
Use Case | Is Node.js Good? |
---|---|
REST APIs | ā Excellent |
Real-time apps (chat, WebSocket) | ā Best choice |
Lightweight microservices | ā Ideal |
CPU-heavy computation | ā Not ideal (better with Go, Rust) |