Beginner Guide to Express.js: Building a Sum to N Backend API

Start your web development journey by building a basic backend using Express.js

ยท

4 min read

1. Project Setup and Basic HTTP Request

Initializing the Project

// Import Express
const express = require('express');

// Create Express application
const app = express();

// Define port
const port = 3000;

// Start the server
app.listen(port, function () {
    console.log(`Example app listening on port ${port}!`);
});

Understanding the Basic Structure

  • express() creates an application

  • app.listen() starts the server

2. Creating the Sum to N Function

// Core calculation function
function sumToN(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

Function Working

  • Takes a number n as input

  • Calculates sum of all numbers from 1 to n

3. Routes and URL Handling

URL vs Route

๐Ÿ‘‰ https://www.google.com/search ๐Ÿ‘ˆ

Different Route Types

Home Route

// Basic home route
app.get('/', function (req, res) {
    res.send('Hello Aditya! This is your homepage.');
});

GET Request with Query Parameter

Using /route1sum route -

// route name: route1sum
app.get('/route1sum', function (req, res) {
    // Extract number from query parameter
    const n = req.query.n;
    const total = sumToN(n);

    // Respond with JSON
    res.json(`this is ${total}`);
});

Response with HTML, JSON & Simple text

Using /route2sum route -

// route name: route2sum
app.get('/route2sum', function (req, res) {
    const n = parseInt(req.query.n);
    const total = sumToN(n);

    // Choose the response format based on the 'format' query parameter
    // Default to HTML if format is not specified
    const format = req.query.format || 'html';  

    if (format === 'json') {
        res.status(200).json({ "total": total });
    } else if (format === 'text') {
        res.status(200).send(`The sum of numbers from 1 to ${n} is: ${total}`);
    } else {
        // Default to HTML
        const html_result = `<h1>${total}</h1>`;
        res.status(200).send(html_result);
    }
});

Output

  • Input for all formats: /route2sum?n=10&format=json, /route2sum?n=10&format=text, /route2sum?n=10

  • JSON Output:

          { "total": 55 }
    
  • Text Output:

      The sum of numbers from 1 to 10 is: 55
    
  • HTML Output:

      <h1>55</h1>
    

GET Request with Header

app.get('/route2sum', function (req, res) {
    // parseInt function is used to parse a string and return an integer value
    const n = parseInt(req.headers.n);
    const total = sumToN(n);

    res.status(200).json({
        total: total
    });
});

POST Request with Body

app.post('/route3sum', function (req, res) {
    // Middleware is needed to parse the request body before accessing req.body.
    // Without middleware like 'express.json()', req.body would be undefined or empty.

    // Extract number from request body
    const n = req.body.n;
    const total = sumToN(n);

    // Respond with status and result
    res.status(200).send({ total: total });
});

Note: Middleware is needed to parse the request body before accessing req.body. Without middleware like express.json(), req.body would be undefined or empty.

POST Request with Body (Including Middleware)
app.use(express.json()); // <= middleware

app.post('/route3sum', function (req, res) {
    // Middleware is needed to parse the request body before accessing req.body.
    // Without middleware like 'express.json()', req.body would be undefined or empty.

    // Extract number from request body
    const n = req.body.n;
    const total = sumToN(n);

    // Respond with status and result
    res.status(200).send({ total: total });
});

4. Request Parameters

Types of Parameters

Query Parameters

// URL: /route1sum?n=10
const n = req.query.n;

Headers Parameters

// Use postman to pass header param
const n = req.headers.n;

Body Parameters

// Requires body-parsing middleware
const n = req.body.n;

Adding Body Parser Middleware

// Enable JSON body parsing
app.use(express.json());

5. Middleware Implementation

Basic Middleware

function middleware1(req, res, next) {
    console.log('inside middleware1');

    // Validate query parameter
    if (!req.query.n) {
        return next(new Error('User query parameter is required'));
    }

    next(); // Continue to next middleware/route handler
}

Error Handling Middleware

function errHandle(err, req, res, next) {
    console.error(err.message);
    res.status(500).send('Something went wrong!');
}

// Apply mutple middleware ware
app.use(middleware1);
app.use(errHandle);

In JavaScript middleware, the next() function is used to pass control to the next middleware function in the stack. When next() is called, it indicates that the current middleware has finished processing and the request should move on to the next function. Next function could be next middleware as well as called api route.

6. Status Codes

Common HTTP Status Codes

  • 200: OK

  • 201: Created

  • 400: Bad Request

  • 404: Not Found

  • 500: Internal Server Error

// Successful response
res.status(200).send(result);

// Error response
res.status(500).send('Server error');

Complete Integrated Example

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

// Middleware
app.use(express.json());

// Sum to N Function
function sumToN(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

// Routes
app.get('/', (req, res) => {
    res.send('Homepage');
});

app.get('/sum', (req, res) => {
    const n = req.query.n;
    const total = sumToN(Number(n));
    res.json({ result: total });
});

// Start Server
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

Key Takeaways

  • Express simplifies backend API creation

  • Multiple route types support different request methods

  • Middleware provides request processing flexibility

  • Always validate and handle input parameters

  • Use appropriate status codes and response formats

ย