DEV Community

Cover image for Building a Serverless Number Classification API with AWS Lambda and API Gateway
Goodluck Ekeoma Adiole
Goodluck Ekeoma Adiole

Posted on

Building a Serverless Number Classification API with AWS Lambda and API Gateway

Introduction

In an era where efficiency and scalability are key, serverless computing is revolutionizing how we build and deploy applications. In this article, I will walk you through the process of developing a Number Classification API, a serverless application hosted on AWS Lambda and exposed via API Gateway. The API analyzes an input number and determines its mathematical properties, such as whether it is prime, even, odd, perfect, or an Armstrong number. Additionally, it fetches a fun fact about the number from an external API.

Project Overview

The Number Classification API accepts a number as a query parameter, processes it, and returns JSON data containing:

  • Whether the number is prime or perfect.
  • Its sum of digits.
  • Whether it is odd or even.
  • A fun fact retrieved from the Numbers API.

The API is publicly accessible, deployed on AWS Lambda, and integrated with API Gateway to serve HTTP requests.

Technology Stack

  • Python: Programming language for the API logic.
  • AWS Lambda: Serverless function execution.
  • API Gateway: RESTful API exposure.
  • S3: Storage for Lambda deployment package.
  • AWS IAM: Access control and security.
  • Boto3: AWS SDK for Python.
  • Requests: Library to interact with the Numbers API.

Setting Up the Project

1. Project Structure

number-classifier-api/
│── package/
│   ├── classifier.py
│── lambda_function.py
│── requirements.txt
│── deployment.zip
│── README.md
Enter fullscreen mode Exit fullscreen mode

2. Installing Dependencies

Before packaging the Lambda function, install the required dependencies:

pip install -r requirements.txt -t package/
Enter fullscreen mode Exit fullscreen mode

3. Writing the Number Classifier Logic

Create a file classifier.py to handle number classification:

import math
import requests

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

def is_armstrong(n):
    digits = [int(d) for d in str(n)]
    return sum(d**len(digits) for d in digits) == n

def get_fun_fact(number):
    url = f"http://numbersapi.com/{number}/math"
    response = requests.get(url)
    return response.text if response.status_code == 200 else "No fact found."

def classify_number(number):
    properties = []
    if is_armstrong(number):
        properties.append("armstrong")
    properties.append("odd" if number % 2 else "even")
    return {
        "number": number,
        "is_prime": is_prime(number),
        "is_perfect": False,  # Simplified for now
        "properties": properties,
        "digit_sum": sum(int(digit) for digit in str(number)),
        "fun_fact": get_fun_fact(number)
    }
Enter fullscreen mode Exit fullscreen mode

4. Writing the AWS Lambda Handler

Create lambda_function.py to handle API Gateway requests:

import json
from classifier import classify_number

def lambda_handler(event, context):
    try:
        number = int(event["queryStringParameters"]["number"])
        result = classify_number(number)
        return {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"},
            "body": json.dumps(result)
        }
    except (ValueError, TypeError, KeyError):
        return {
            "statusCode": 400,
            "headers": {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"},
            "body": json.dumps({"error": "Invalid input. Provide a valid integer."})
        }
Enter fullscreen mode Exit fullscreen mode

5. Packaging and Deploying to AWS Lambda

Compress dependencies and source files into deployment.zip:

cd package
zip -r ../deployment.zip .
cd ..
zip -g deployment.zip lambda_function.py classifier.py
Enter fullscreen mode Exit fullscreen mode

Upload the package to AWS Lambda:

aws lambda create-function --function-name number-classifier-api \
  --runtime python3.8 --role <IAM_ROLE_ARN> \
  --handler lambda_function.lambda_handler --timeout 10 \
  --memory-size 128 --zip-file fileb://deployment.zip
Enter fullscreen mode Exit fullscreen mode

6. Configuring API Gateway

Create an API Gateway GET method and integrate it with the Lambda function:

aws apigateway create-resource --rest-api-id <API_ID> --parent-id <PARENT_ID> --path-part api
aws apigateway put-method --rest-api-id <API_ID> --resource-id <RESOURCE_ID> --http-method GET --authorization-type NONE
aws apigateway put-integration --rest-api-id <API_ID> --resource-id <RESOURCE_ID> \
  --http-method GET --type AWS_PROXY --integration-http-method POST \
  --uri arn:aws:lambda:<REGION>:<ACCOUNT_ID>:function:number-classifier-api
Enter fullscreen mode Exit fullscreen mode

Deploy the API:

aws apigateway create-deployment --rest-api-id <API_ID> --stage-name prod
Enter fullscreen mode Exit fullscreen mode

Enable Lambda invocation permissions:

aws lambda add-permission --function-name number-classifier-api \
  --statement-id apigateway-access --action lambda:InvokeFunction \
  --principal apigateway.amazonaws.com
Enter fullscreen mode Exit fullscreen mode

Testing the API

After deployment, access the API via:

https://<API_ID>.execute-api.<REGION>.amazonaws.com/prod/api/classify-number?number=371
Enter fullscreen mode Exit fullscreen mode

Example Response:

{
    "number": 371,
    "is_prime": false,
    "is_perfect": false,
    "properties": ["armstrong", "odd"],
    "digit_sum": 11,
    "fun_fact": "371 is an Armstrong number because 3^3 + 7^3 + 1^3 = 371"
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

By leveraging AWS Lambda and API Gateway, we built a scalable, cost-efficient, and serverless Number Classification API. This approach eliminates the need to manage servers while providing a fast and reliable solution.
You can extend this project by integrating caching mechanisms or additional number properties.

Let me know in the comments if you have any questions or suggestions! 🚀

Top comments (0)