Technology • 2024-06-25

Node.js for Beginners: Build Your First Backend API

Learn Node.js from scratch — event loop, Express.js, REST API creation, connecting to MongoDB, and building a simple calculator API.

Node.jsBackend DevelopmentExpress.jsWeb API
⏱ 2 min read

Why Node.js?

Node.js lets you use JavaScript on the server side — one language for both frontend and backend. It's the technology behind large-scale applications at LinkedIn, Netflix, Uber, and PayPal. In India, Node.js is widely used in startups and product companies. It's particularly good for real-time applications and APIs.

Setting Up Node.js

# Install Node.js from nodejs.org (LTS version)
# Verify installation:
node --version  # v20.x.x
npm --version   # 10.x.x

# Initialize a project:
mkdir my-api && cd my-api
npm init -y

Your First Node.js Script

// hello.js
console.log("Namaste from Node.js!");

// Read a file
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

// HTTP server (no Express)
const http = require('http');
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello from Node.js server!');
});
server.listen(3000, () => console.log('Server running on port 3000'));

Express.js: The Web Framework

npm install express

// server.js
const express = require('express');
const app = express();
app.use(express.json()); // Parse JSON request bodies

// Routes
app.get('/', (req, res) => {
    res.json({ message: 'Welcome to AMTools API!' });
});

// EMI Calculator API endpoint
app.post('/api/emi', (req, res) => {
    const { principal, rate, months } = req.body;
    const r = rate / 100 / 12;
    const emi = (principal * r * Math.pow(1+r, months)) / (Math.pow(1+r, months) - 1);
    res.json({
        emi: Math.round(emi),
        totalAmount: Math.round(emi * months),
        totalInterest: Math.round((emi * months) - principal)
    });
});

// GST Calculator API endpoint
app.post('/api/gst', (req, res) => {
    const { amount, rate } = req.body;
    const gst = amount * rate / 100;
    res.json({ originalAmount: amount, gstAmount: gst, totalAmount: amount + gst });
});

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

// Test: POST /api/emi with { "principal": 500000, "rate": 8.5, "months": 60 }

Connecting to MongoDB

npm install mongoose

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp');

// Define schema
const UserSchema = new mongoose.Schema({
    name: String,
    email: { type: String, unique: true },
    createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', UserSchema);

// Create user
app.post('/users', async (req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).json(user);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
});

Learning Path

1) JavaScript fundamentals (especially async/await, promises) 2) Node.js core modules 3) Express.js 4) Database (MongoDB via Mongoose or PostgreSQL via pg) 5) Authentication (JWT) 6) Deployment (Render.com, Railway, Vercel Functions — free tiers available)