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. Overview of the Solution The Number Classification API performs the following tasks: Accepts a number via an HTTP GET request. Determines whether the number is prime, perfect, or Armstrong. Computes the sum of its digits. Fetches an interesting mathematical fact using the Numbers API. Returns a well-structured JSON response. Solution Architecture User Request: A client (browser or app) sends a number to the API via an HTTP GET request. API Gateway: Serves as the entry point, invoking the AWS Lambda function. AWS Lambda: Executes the number classification logic and fetches fun facts. External Numbers API: Provides mathematical trivia for the input number. Response: The Lambda function returns a JSON response containing the computed results. Step-by-Step Implementation Step 1: Create the Lambda Function Navigate to the AWS Lambda Console and create a new function. Choose "Author from Scratch" and select Python as the runtime. 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://numbersapi.com/{number}/math" 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 }) } Step 2: Set Up API Gateway Navigate to the API Gateway Console and create a new API. Connect it to the Lambda function using Lambda Proxy Integration. Deploy the API and obtain the endpoint URL. 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 GET https://mia36nbu21.execute-api.us-east-1.amazonaws.com/api/classify-number?number=371 Example Successful Response (200 OK) Error Response (400 Bad Request) Project Deployment and Code Hosting The project code is publicly available on GitHub. The API is deployed at AWS API Gateway Endpoint. 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.
![Serverless Computing: Building a Number Classification API with AWS Lambda and API Gateway](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fvia.placeholder.com%2F800x350.png)
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.
Overview of the Solution
The Number Classification API performs the following tasks:
- Accepts a number via an HTTP GET request.
- Determines whether the number is prime, perfect, or Armstrong.
- Computes the sum of its digits.
- Fetches an interesting mathematical fact using the Numbers API.
- Returns a well-structured JSON response.
Solution Architecture
- User Request: A client (browser or app) sends a number to the API via an HTTP GET request.
- API Gateway: Serves as the entry point, invoking the AWS Lambda function.
- AWS Lambda: Executes the number classification logic and fetches fun facts.
- External Numbers API: Provides mathematical trivia for the input number.
- Response: The Lambda function returns a JSON response containing the computed results.
Step-by-Step Implementation
Step 1: Create the Lambda Function
- Navigate to the AWS Lambda Console and create a new function.
- Choose "Author from Scratch" and select Python as the runtime.
- 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://numbersapi.com/{number}/math"
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
})
}
Step 2: Set Up API Gateway
- Navigate to the API Gateway Console and create a new API.
- Connect it to the Lambda function using Lambda Proxy Integration.
- Deploy the API and obtain the endpoint URL.
- 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
GET https://mia36nbu21.execute-api.us-east-1.amazonaws.com/api/classify-number?number=371
Example Successful Response (200 OK)
Error Response (400 Bad Request)
Project Deployment and Code Hosting
- The project code is publicly available on GitHub.
- The API is deployed at AWS API Gateway Endpoint.
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.