DEV Community

Adetola Hannah
Adetola Hannah

Posted on

Deploying a Simple Number Classification API with Node.js and Render

In the world of machine learning and artificial intelligence, classification tasks play a crucial role in sorting and analyzing data. One such task is number classification, which involves determining whether a given number is positive, negative, or zero. In this blog post, we'll explore how to build a simple Number Classification API using Node.js.

Introduction

The Number Classification API is a lightweight RESTful service built with Node.js and Express.js. It takes a number as input and returns its classification: positive, negative, or zero. This API is useful for educational purposes, small-scale applications, and learning the basics of API development.

Setting Up the Project

To get started, clone the repository from GitHub:

$ git clone https://github.com/ajalaadetola/number-classification-api.git
$ cd number-classification-api
Enter fullscreen mode Exit fullscreen mode

Next, install the required dependencies:

$ npm install
Enter fullscreen mode Exit fullscreen mode

Understanding the Code

Let's break down the core logic of the API. The main entry point of the application is index.js. Here’s a look at its key components:

1. Importing Dependencies

const express = require('express');
const app = express();
Enter fullscreen mode Exit fullscreen mode

We use Express.js to set up a simple web server.

2. Creating the Classification Logic

// API Endpoint
app.get("/api/classify-number", async (req, res) => {
    const { number } = req.query;

    // Validate input: Ensure the number is provided and valid
    if (!number || isNaN(number)) {
        return res.status(400).json({ 
            number,  // ✅ Include the invalid input as it was received
            error: "Invalid number" 
        });
    }

    const num = Number(number); // Convert to a valid number

    const properties = [];
    if (isArmstrong(num)) properties.push("armstrong");
    properties.push(num % 2 === 0 ? "even" : "odd");

    const funFact = await getFunFact(num);

    // ✅ Fix: Ensure digit_sum is numeric, even for negative numbers
    const digitSum = Math.abs(num)
        .toString()
        .split("")
        .filter(char => !isNaN(char)) // Remove non-numeric characters like "-"
        .reduce((sum, digit) => sum + parseInt(digit), 0);

    res.json({
        number: num,
        is_prime: isPrime(num),
        is_perfect: isPerfect(num),
        properties,
        digit_sum: digitSum,
        fun_fact: funFact
    });
});
Enter fullscreen mode Exit fullscreen mode

3. Running the Server

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

This sets up the server to listen on port 3000 or an environment-specified port.

Testing the API

You can test the API locally using Postman or your web browser. Start the server:

$ node index.js
Enter fullscreen mode Exit fullscreen mode

Then, open your browser and enter the following URL:

http://localhost:3000/api/classify-number?number=10
Enter fullscreen mode Exit fullscreen mode

You should receive a response like:

{
  "digit_sum": 11,
  "fun_fact": "371 is a narcissistic number.",
  "is_perfect": false,
  "is_prime": false,
  "number": 371,
  "properties": [
    "armstrong",
    "odd"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Deploying the API on Render

You can deploy this API using Render, a cloud hosting platform that provides seamless deployment for Node.js applications.

Steps to Deploy on Render:

  1. Create an account on Render.
  2. Click New Web Service and connect your GitHub repository.
  3. Select the repository number-classification-api.
  4. Set the runtime environment to Node.js.
  5. Configure the start command as:
   node index.js
Enter fullscreen mode Exit fullscreen mode
  1. Click Deploy and wait for the build to complete.

Once deployed, Render will provide a public URL where your API can be accessed.

Conclusion

This simple Number Classification API demonstrates how to build and deploy a basic REST API using Node.js and Express.js. By understanding the fundamentals of request handling and data validation, you can extend this project further—perhaps by integrating a machine learning model for more complex classifications.

Check out the full code on GitHub: Number Classification API 🚀.

Happy coding! 🎉

Top comments (0)