Project Overview:
We are building an API that takes a number as input and returns interesting mathematical properties about it, along with a fun fact related to that number. The API will be deployed using a serverless architecture, leveraging AWS Lambda for the backend and API Gateway to expose the API to users.
Key Features:
Mathematical Properties: The API will determine properties such as:
- Parity: Whether the number is even or odd.
- Prime Status: Whether the number is prime.
- Factors: The factors of the number.
- Square and Cube: The square and cube of the number.
- These properties will be calculated programmatically using Python.
Fun Fact: The API will fetch a fun fact about the number using the Numbers API This API provides interesting trivia related to numbers.
Tech Stack:
Python:
- The core logic for calculating mathematical properties will be written in Python.
- Python libraries like
requests
will be used to interact with external APIs (e.g., Numbers API).
AWS Lambda:
- The API logic will be deployed as a serverless function using AWS Lambda.
- Lambda is ideal for this use case because it scales automatically and is cost-effective for low-to-moderate traffic.
API Gateway:
- AWS API Gateway will be used to create a RESTful API endpoint that triggers the Lambda function.
- It will handle incoming HTTP requests (e.g.,
GET /number/{number}
) and pass the input to the Lambda function.
Mangum Adapter:
- Since AWS Lambda expects events in a specific format, we will use the Mangum library to adapt our Python web application (e.g., built with FastAPI or Flask) to work seamlessly with Lambda.
NumbersAPI/
│── lambda_function.py
│── requirements.txt
└── package/
Update requirements.txt :
-
FastAPI: provides a high performance, asynchronous API framework.
I had to specify with the fastapi specific versions, so ensure you choose the
0.99.0
Got the solution from stackoverflow Mangum: enables seamless deployment of fast api to AWS Lambda.
Requests: allows external API calls to enrich responses.
fastapi==0.99.0
mangum
requests
Create lambda_function.py:
I used Claude AI to generate the below python lambda function:
The function is used classify numbers based on mathematical properties and fetch fun facts about them. It includes CORS configuration for cross-origin requests and is designed to be deployed on AWS Lambda using Mangum.
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from mangum import Mangum
import requests
import math
from fastapi.responses import JSONResponse
app = FastAPI()
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(math.sqrt(abs(n))) + 1):
if n % i == 0:
return False
return True
def is_perfect(n: int) -> bool:
if n <= 1:
return False
sum_divisors = 1
for i in range(2, int(math.sqrt(abs(n))) + 1):
if n % i == 0:
sum_divisors += i
if i != n // i:
sum_divisors += n // i
return sum_divisors == abs(n)
def is_armstrong(n: int) -> bool:
num_str = str(abs(n))
num_digits = len(num_str)
return sum(int(d) ** num_digits for d in num_str) == abs(n)
def get_digit_sum(n: int) -> int:
return sum(int(d) for d in str(abs(n)))
def get_properties(n: int) -> list:
properties = []
if is_armstrong(n):
properties.append("armstrong")
if n % 2 == 0:
properties.append("even")
else:
properties.append("odd")
return properties
def get_fun_fact(n: int) -> str:
try:
response = requests.get(f"http://numbersapi.com/{n}/math")
fact = response.text
return fact.replace("\n", "").strip()
except:
return f"{n} is a number"
@app.get("/api/classify-number")
async def classify_number(number: str):
# Input validation
if not number:
return JSONResponse(
status_code=400,
content={"number": None, "error": True}
)
try:
# Convert to float first to handle decimal points
num_float = float(number)
# Convert to integer (truncating any decimal part)
num = int(num_float)
response_data = {
"number": num,
"is_prime": is_prime(num),
"is_perfect": is_perfect(num),
"properties": get_properties(num),
"digit_sum": get_digit_sum(num),
"fun_fact": get_fun_fact(num)
}
return JSONResponse(
status_code=200,
content=response_data
)
except ValueError:
return JSONResponse(
status_code=400,
content={"number": number, "error": True}
)
except Exception as e:
return JSONResponse(
status_code=500,
content={"number": number, "error": True}
)
# Handler for AWS Lambda
handler = Mangum(app)
Create a deployment package:
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Create package directory
mkdir package
# Install dependencies in package directory
pip install --target ./package -r requirements.txt
# Copy lambda function to package
cp lambda_function.py package/
# Create deployment ZIP
cd package
zip -r ../deployment.zip .
cd ..
Deploy using AWS Console:
Create a Lambda function:
Go to AWS Lambda console
Click "Create function"
Choose "Author from scratch"
Name: "number-classifier"
Runtime: Python 3.13 or latest
Create Execution role with basic Lambda permissions
Create function
Upload the code:
Upload the deployment.zip file from your computer
Set the handler to "lambda_function.handler"
Set timeout to 30 seconds
Set memory to 256 MB
Update the IAM role:
-
Edit your attached policy so that it allows Lambda to access CloudWatch Logs and execute API Gateway:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": "arn:aws:execute-api:*:*:*" } ] }
Create API Gateway:
Go to API Gateway console
- Create new REST API
-
Create resource "/api/classify-number"
- First Create the /api Resource
- Then create the /api/classify-number resource from the /api/ resource path
-
Create method:
- Select GET as the method type
- Select Integration type: Lambda Function
- Enable Lambda proxy integration
- Select your lambda function created earlier: ensure correct region selected
API is accessible at: https://[YOUR-API-ID].execute-api.[REGION].amazonaws.com/prod/api/classify-number?number=371
To test the deployed API:
curl "https://[YOUR-API-ID].execute-api.[REGION].amazonaws.com/prod/api/classify-number?number=371"
You can also test using your web browser:
Remember to:
Replace placeholder values with your actual AWS account details
Configure appropriate IAM roles and permissions
Enable CORS if needed
Set appropriate timeout values
Monitor CloudWatch logs for any issues
Test thoroughly before submission
Next Steps:
Deploy using AWS CLI
Deploy using terraform
A UI to interact with the API
Lets Connect - Lewis Sawe
Top comments (0)