HNG Internship: DevOps Stage 1 - Number Classification API

·

3 min read

HNG Internship: DevOps Stage 1 - Number Classification API

This week the HNG Internship begins with a more serious application. The task for the week is to create a number classification APi that takes in a number and return Funfact about the number in Json format. for this task. i utilize the Aws lambda function and API-gateway in this task.

Deploying the API with Lambda and API Gateway

Deploy the Lambda Function

  1. Go to the AWS Lambda Console.

  2. Create a new function

  3. Copy and paste the code.

  4. Save and deploy the function.

     import json
     import math
     import requests
    
     def lambda_handler(event, context):
         try:
             # Extract the number from the query string parameters
             number = int(event['queryStringParameters']['number'])
    
             # Determine if the number is prime
             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
    
             # Determine if the number is perfect
             def is_perfect(n):
                 return n > 1 and sum(i for i in range(1, n) if n % i == 0) == n
    
             # Determine if the number is an Armstrong number
             def is_armstrong(n):
                 digits = [int(d) for d in str(n)]
                 power = len(digits)
                 return sum(d ** power for d in digits) == n
    
             # Fetch fun fact from Numbers API
             fun_fact_api_url = f"http://numbersapi.com/{number}"
             fun_fact_response = requests.get(fun_fact_api_url)
             fun_fact = fun_fact_response.text if fun_fact_response.ok else "No fun fact available."
    
             # Compute properties
             properties = []
             if is_armstrong(number):
                 properties.append("armstrong")
             if number % 2 == 0:
                 properties.append("even")
             else:
                 properties.append("odd")
    
             # Build the response
             response_body = {
                 "number": number,
                 "is_prime": is_prime(number),
                 "is_perfect": is_perfect(number),
                 "properties": properties,
                 "digit_sum": sum(int(digit) for digit in str(number)),
                 "fun_fact": fun_fact
             }
    
             return {
                 "statusCode": 200,
                 "headers": {
                     "Access-Control-Allow-Origin": "*",
                     "Access-Control-Allow-Methods": "GET",
                     "Access-Control-Allow-Headers": "Content-Type"
                 },
                 "body": json.dumps(response_body)
             }
    
         except (ValueError, KeyError):
             return {
                 "statusCode": 400,
                 "headers": {
                     "Access-Control-Allow-Origin": "*",
                     "Access-Control-Allow-Methods": "GET",
                     "Access-Control-Allow-Headers": "Content-Type"
                 },
                 "body": json.dumps({"error": True, "message": "Invalid number input."})
             }
    

Enable the requests Library

  • Create a Directory for the Layer Open your terminal and create a directory structure:

      mkdir python-lambda-layer
      cd python-lambda-layer
      mkdir python
    
  • Install the requests Library Locally Inside the python-lambda-layer/python directory, run:

      pip install requests -t .
    

    This will download the requests library and its dependencies into the python directory.

  • Zip the Directory Zip the contents for uploading to AWS:

      cd ..
      zip -r requests-layer.zip python
    
  • Upload the Layer to AWS Lambda

    • Navigate to the AWS Lambda Console.

    • Select Layers from the left menu.

    • Click Create layer.

    • Provide a name (e.g., requests-layer).

    • Upload your requests-layer.zip.

    • Set the runtime (e.g., Python 3.8 or 3.9, depending on your Lambda runtime).

Attach the Layer to Your Lambda Function

  • Open your Lambda function in the AWS console.

  • Go to the Layers section and click Add a layer.

  • Choose your uploaded layer (requests-layer) and add it.

Create API Gateway

  • Navigate to API Gateway in AWS.

  • Create a new HTTP API.

  • Add a GET Method.

  • Link it to your Lambda function.

  • Enable CORS for cross-origin requests (important for browser-based apps).

  • Deploy the API to a Stage.

when this is done, the api-gateway will show in the lambda function indicating it has been attached to it as a trigger.

Api End-point Url : https://24f4plfe8f.execute-api.us-east-1.amazonaws.com/api/classify-number?number=70

Bonus : I also built a simple application using the API end-point where users can input a number in the field and clink on submit and the fun fact about the number will be displayed on the screen.

You can test it here App

You can find my Code on Github