DEV Community

Cover image for Building a Number Classification API using AWS Lambda.
Tony Uketui
Tony Uketui

Posted on

Building a Number Classification API using AWS Lambda.

Deploying APIs can be complex, but AWS Lambda simplifies the process with a serverless, cost-effective, and scalable approach. Instead of managing servers, Lambda runs only when triggered, making it perfect for low-traffic APIs. In this project, I built a number classification API using AWS Lambda, API Gateway, and Python, ensuring fast execution and minimal costs. Here’s how I did it. 🚀

Why Use Lambda?

Before diving into this project, it's important to understand what our API is doing and why we're using AWS Lambda instead of other deployment methods.

There are multiple ways to make an API publicly accessible:

  • EC2: I initially deployed an API using Amazon EC2, which required setting up a virtual server, installing dependencies, and managing uptime.
  • Vercel, Render & Elastic Beanstalk: Both provide managed environments for running applications with minimal configuration.

However, for this project, I chose AWS Lambda because it is serverless—meaning I don't need to manage servers. AWS automatically provisions the infrastructure, executes the code, and shuts down after execution, making it highly cost-effective since I'm only billed when the function runs.

This is perfect for low-traffic APIs like this one. Instead of keeping an EC2 instance running all the time, Lambda only executes when a request is made.

Additionally, Lambda functions run in milliseconds, making it incredibly fast.

In summary, AWS Lambda was the best choice because it is:

Lightweight—Runs only when triggered

Cost-effective—No server maintenance costs

Fast—Executes within milliseconds

Fully managed—AWS handles scaling and availability


How the API Works (Simplified Explanation)

The API is designed to classify a number based on its properties and return some interesting facts. The flow works as follows:

  1. A user requests the API
  2. The API Gateway forwards the request to AWS Lambda
  3. AWS Lambda processes the request and generates a response
  4. The API Gateway sends the response back to the user

Analogy: Restaurant Example

If this concept is unclear, think of it like a restaurant:

  • You (the user) walk into a restaurant and place an order
  • The waiter (API Gateway) takes your order to the kitchen
  • The kitchen (AWS Lambda) prepares the meal
  • The waiter brings the meal back to you

Just like how you don’t need to know how the kitchen operates, the user doesn’t need to worry about the backend—Lambda handles everything behind the scenes.


Step 1: Setting Up AWS Lambda

I logged into AWS Lambda, clicked "Create Function", and chose "Author from Scratch" with the following settings:

  • Runtime: Python 3.x
  • Permissions: Created a new execution role with basic Lambda permissions

Image description


Step 2: Writing the Lambda Function (Python)

I wrote a Python function that classifies a number and returns its properties. It checks for:

Prime numbers

Armstrong numbers

Even or odd classification

Sum of digits

A fun fact about the number (using Numbers API)

Here’s the function:

import json
import math
import requests

# Function to check if a number is prime
def is_prime(n):
    if n < 2:
        return False
    if n in (2, 3):
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    for i in range(5, int(math.sqrt(n)) + 1, 2):
        if n % i == 0:
            return False
    return True

# Function to check if a number is an Armstrong number
def is_armstrong(n):
    if n < 0:
        return False
    digits = [int(digit) for digit in str(n)]
    power = len(digits)
    return sum(digit ** power for digit in digits) == n

# Function to check if a number is a perfect number
def is_perfect(n):
    if n < 1:
        return False
    return sum(i for i in range(1, n // 2 + 1) if n % i == 0) == n

# Function to get a fun fact about the number
def get_fun_fact(n):
    if n < 0:
        return "Fun fact not available for negative numbers."
    try:
        response = requests.get(f"http://numbersapi.com/{n}/math", 2timeout=5)
        if response.status_code == 200:
            return response.text
    except requests.exceptions.RequestException:
        pass
    return "Fun fact not available."

# AWS Lambda Handler
def lambda_handler(event, context):
    query_params = event.get("queryStringParameters", {})
    number_str = query_params.get("number") if query_params else None

    if not number_str:
        return {
            "statusCode": 400,
             "headers": {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "GET",
                "Access-Control-Allow-Headers": "Content-Type"
 2           },
            "body": json.dumps({"error": "No number provided."})
        }

    try:
        number = int(float(number_str))
    except ValueError:
        return {
            "statusCode": 400,
             "headers": {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "GET",
                "Access-Control-Allow-Headers": "content-type"
            },
            "body": json.dumps({
                "error": "Invalid number format",
                 'invalid_input': number_str  # Include the invalid input in the response
                })
        }

    properties = ["odd" if number % 2 else "even"]
    if is_armstrong(number):
        properties.insert(0, "armstrong")

    response_body = {
        "number": number,
        "is_prime": is_prime(number),
        "is_perfect": is_perfect(number),
        "properties": properties,
        "digit_sum": sum(int(d) for d in str(abs(number))),
        "fun_fact": get_fun_fact(number)
    }

    return {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET",
            "Access-Control-Allow-Headers": "Content-Type"
        },
        "body": json.dumps(response_body)
    }
Enter fullscreen mode Exit fullscreen mode

Step 3: Deploying API Gateway

To make the function accessible via an HTTP request, I integrated it with AWS API Gateway:

  1. Went to API Gateway
  2. Created a new HTTP API
  3. Set up a GET method
  4. Integrated it with my Lambda function
  5. Enabled CORS to allow frontend applications to call the API

Image description

Image description

After deployment, I got a public API endpoint like this:

https://taeiej1dj0.execute-api.us-east-1.amazonaws.com/prod/api/classify-number?number=371

Step 4: Testing the API

I tested the API using my browser

When I sent a valid request i got the required information and a 200 status code:

https://taeiej1dj0.execute-api.us-east-1.amazonaws.com/prod/api/classify-number?number=800
Enter fullscreen mode Exit fullscreen mode

Image description

If I sent an invalid request (e.g., letters instead of numbers), I received a 400 Bad Request response:

Image description

If I didnt send any request (e.g no number or letter), I received a 400 Bad Request response:

Image description

Step 5: Hosting the Code on GitHub

Since I needed Version control, I:

  1. Created a public GitHub repository
  2. Pushed my Lambda function code with a well-structured README.md

🔗 GitHub Repo: [https://github.com/Anthonyuketui/API-NumberClasifier]

Conclusion

AWS Lambda is serverless—no need to manage infrastructure

API Gateway makes the function publicly accessible

CORS enabled—any frontend can call the API

Fast & lightweight—response time under 500ms

This setup provides a scalable, cost-effective, and efficient way to deploy APIs without managing a web server.

Top comments (5)

Collapse
 
favxlaw profile image
Favour Lawrence

Very detailed

Collapse
 
tony_uketui_6cca68c7eba02 profile image
Tony Uketui

Thanks🙌

Collapse
 
starrinthecloud profile image
folashade oluwaseun

Nice

Collapse
 
tony_uketui_6cca68c7eba02 profile image
Tony Uketui

Thanks🙌

Collapse
 
patrick_ibe profile image
patrick ibe

Thank you for this!!