Building a Number Classification API with AWS Lambda & API Gateway

B.G.Skillz 🧑‍💻 - Feb 8 - - Dev Community

Introduction

In the world of DevOps, deploying a scalable and serverless API is a valuable skill. This blog post walks you through building a Number Classification API using AWS Lambda, API Gateway, and Python. The API takes a number as input and returns its mathematical properties along with a fun fact.

I have used Local Machine to perform the task but I am having issue with the Deployment. After making many attempt to use the local machine it doesnt work out. I decided to use AWS Lamba and import my code to the code editor

CREATING OF THE FUNCTION
I navigate to my Console home and search for Lambda then select and create a function number-classifcation-api

WHY I CHOOSE LAMBA
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.

Image description

After create the function I import my code

import json
import math
import urllib.request
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
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
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

def get_fun_fact(n):
    if n < 0:
        return "Fun fact not available for negative numbers."
    try:
        url = f"http://numbersapi.com/{n}/math"
        with urllib.request.urlopen(url, timeout=5) as response:
            return response.read().decode("utf-8")
    except Exception:
        return "Fun fact not available."
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"
            },
            "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

After importing the code I test the code before deploying it was working

Image description

How the API Works

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

A user requests the API
The API Gateway forwards the request to AWS Lambda
AWS Lambda processes the request and generates a response
The API Gateway sends the response back to the user

Setting Up API Gateway

  • Go to AWS API Gateway → Create API
  • Choose REST API → New API
  • Set Endpoint as Lambda Function
  • Define Resource Path /api/classify-number
  • Enable CORS (for cross-origin requests)
  • Deploy the API to a stage (prod)

After that I navigate to the APIGateway to create the API and named it NumberClassificationAPI then use GET to create the path /api/classfiy-api and I deploy the stage using (prod) and I enable CORS then I deploy it.
(https://nr7acfudff.execute-api.us-east-1.amazonaws.com/prod/api/classify-number?number=371)

(https://github.com/Bolarinwa2030/Lambda_function/tree/main)

Image description

Image description

This is output

. . . .