🔢 I Forced AWS to Do Math for Me: Building a Number Wizard API

"They said 'build an API that does math' – they didn't say I'd need therapy after."

What started as a simple HNG internship task turned into an adventure through AWS Lambda, mathematical algorithms, and the occasional existential crisis. Here's how I built a number-crunching API and lived to tell the tale.

API requirements
The seemingly innocent API requirements that started it all

📜 The Quest: Become a Number Whisperer

The task seemed simple enough on paper, but quickly revealed its complexity:

  • Create a RESTful API endpoint that accepts any integer
  • Determine if the number is odd, even, prime, or composite
  • Check for special properties like being a perfect square or Armstrong number
  • Return fun facts about the number (because why not?)
  • Deploy it to a production environment with proper documentation

What's an Armstrong Number?

An Armstrong number is a number that equals the sum of its own digits each raised to the power of the number of digits. For example, 153 = 1³ + 5³ + 3³. Finding these efficiently became one of my biggest challenges.

🧙‍♂️ Phase 1: Summoning the Lambda Spirit

Architecture Decisions

After considering various options, I settled on AWS Lambda for several reasons:

  • Serverless = no infrastructure management
  • Pay-per-use pricing (perfect for a demo)
  • Easy integration with API Gateway
  • Python runtime for mathematical operations
AWS Lambda console
AWS Lambda console - where the magic happens
lambda_handler.py
def lambda_handler(event, context):
    # Extract the number from the request
    try:
        number = int(event['queryStringParameters']['number'])
    except (KeyError, ValueError, TypeError):
        return {
            'statusCode': 400,
            'headers': {'Access-Control-Allow-Origin': '*'},
            'body': json.dumps({"error": "Please provide a valid integer"})
        }
    
    # Calculate all the properties
    result = {
        'number': number,
        'isEven': is_even(number),
        'isPrime': is_prime(number),
        'factors': get_factors(number),
        'isArmstrong': is_armstrong(number),
        'isPerfectSquare': is_perfect_square(number),
        'funFact': get_fun_fact(number)
    }
    
    return {
        'statusCode': 200,
        'headers': {'Access-Control-Allow-Origin': '*'},
        'body': json.dumps(result)
    }

Key Points: The handler extracts the number, validates it, calculates various properties, and returns a JSON response. The CORS headers were added after a painful debugging session.

⚔️ Battle Report: The Three Boss Fights

Boss 1: Armstrong Number Hydra
# Armstrong number validation
def is_armstrong(n):
    # 371 = 3³ + 7³ + 1³ = 371
    digits = [int(d) for d in str(abs(n))]
    power = len(digits)
    return sum(d**power for d in digits) == abs(n)

Casualty Report: 3 failed attempts, 1 existential crisis

Boss 2: CORS the Gatekeeper
# The magic CORS fix
return {
    'statusCode': 200,
    'headers': {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    },
    'body': json.dumps(response)
}
CORS error
Boss 3: Edge Case Monster
# Edge case handling examples
✅ Negative numbers: is_prime(-7) → False
✅ Zero: get_factors(0) → "All integers"
✅ Large numbers: timeout handling
✅ Non-numeric: "banana" → 400 Error

# Validation snippet
try:
    number = int(event['queryStringParameters']['number'])
except (TypeError, ValueError):
    return error_response("Invalid number format")
"The most valuable lessons come from the most embarrassing bugs."

🏆 Victory Conditions Met

~50ms Average Response Time
99.9% Uptime
$0 Monthly Cost

Ready to Make Your Calculator Jealous?

The Number Wizard API is now live and ready to amaze you with its mathematical prowess. Try it out with your favorite numbers!

Warning: May cause unexpected mathematical excitement

Try These Examples:

  • ...?number=371 (Armstrong number)
  • ...?number=42 (The answer to everything)
  • ...?number=1729 (Ramanujan's number)
  • ...?number=🐔 (Chaos mode)