DEV Community

Alao Abdul-zahir
Alao Abdul-zahir

Posted on

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

Serverless computing has revolutionized the way applications are developed and deployed by eliminating the need for traditional server management. This post explores the creation of a Number Classification API using AWS Lambda and API Gateway, a robust combination for building highly scalable and cost-effective serverless APIs.

The API is capable of returning mathematical properties for any given number, such as whether it’s a prime, perfect, or Armstrong number, along with other properties and a fun fact.


Why Serverless Computing?

Serverless architecture offers several advantages:

  • Scalability: Automatically handles request scaling without manual intervention.
  • Cost Efficiency: Pay only for the actual usage.
  • Focus on Development: Eliminate server maintenance and infrastructure concerns.

Solution Overview

The Number Classification API performs the following tasks:

  1. Accepts a number via an HTTP GET request.
  2. Determines whether the number is prime, perfect, or Armstrong.
  3. Computes the sum of its digits.
  4. Fetches an interesting mathematical fact using an external numbers API.
  5. Returns a well-structured JSON response.

Architecture

Image description

  1. User Request: A client (browser or app) sends a number to the API via an HTTP GET request.
  2. API Gateway: Serves as the entry point, invoking the AWS Lambda function.
  3. AWS Lambda: Executes the number classification logic and fetches fun facts.
  4. External Numbers API: Provides mathematical trivia for the input number.
  5. Response: The Lambda function returns a JSON response containing the computed results.

Step-by-Step Implementation

Step 1: Create the Lambda Function

  1. Navigate to the AWS Lambda Console and create a new function.
  2. Choose "Author from Scratch" and select Python as the runtime.
  3. Upload the following Lambda code to the function:

Lambda Function Code

import json
import urllib.request

def classify_number(number):
    if number > 1:
        is_prime = all(number % i != 0 for i in range(2, int(number ** 0.5) + 1))
    else:
        is_prime = False

    is_perfect = sum(i for i in range(1, number) if number % i == 0) == number

    digits = [int(d) for d in str(number)]
    is_armstrong = sum(d ** len(digits) for d in digits) == number
    digit_sum = sum(digits)

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

    return is_prime, is_perfect, properties, digit_sum

def fetch_fun_fact(number):
    try:
        url = f"http://example.com/{number}/math"  # External API placeholder
        with urllib.request.urlopen(url) as response:
            return response.read().decode()
    except Exception:
        return "Unable to fetch fun fact at the moment."

def lambda_handler(event, context):
    try:
        number = int(event["queryStringParameters"]["number"])
        is_prime, is_perfect, properties, digit_sum = classify_number(number)
        fun_fact = fetch_fun_fact(number)

        return {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps({
                "number": number,
                "is_prime": is_prime,
                "is_perfect": is_perfect,
                "properties": properties,
                "digit_sum": digit_sum,
                "fun_fact": fun_fact
            })
        }
    except (ValueError, KeyError):
        return {
            "statusCode": 400,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps({
                "number": event["queryStringParameters"].get("number", "invalid"),
                "error": True
            })
        }
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up API Gateway

  1. Navigate to the API Gateway Console and create a new API.
  2. Connect it to the Lambda function using Lambda Proxy Integration.
  3. Deploy the API and obtain the endpoint URL.
  4. Enable CORS (Cross-Origin Resource Sharing) for public access.

Testing the API

To test the API, use tools like Postman or simply visit the API URL in your browser.

Example Request (Placeholder)

GET https://example-api-url.com/classify-number?number=371
Enter fullscreen mode Exit fullscreen mode

Example Successful Response (200 OK)

Image description

Error Response (400 Bad Request)

{
  "number": "invalid",
  "error": true
}
Enter fullscreen mode Exit fullscreen mode

  • The project code is publicly available on GitHub.

Conclusion

Serverless computing allows developers to focus on building applications without worrying about infrastructure. By integrating AWS Lambda and API Gateway, a reliable and scalable Number Classification API was successfully built and deployed. This approach showcases the efficiency and versatility of serverless architecture for real-world applications.

Top comments (0)