DEV Community

Cover image for Deploying the Number Classification API Using AWS Lambda Function URL
Richard Atodo
Richard Atodo

Posted on

Deploying the Number Classification API Using AWS Lambda Function URL

Introduction

After completing my Number Classification API for Stage 1 of the HNG DevOps Internship, I deployed it. The goal was to make my API publicly accessible while ensuring seamless integration with AWS Lambda. Instead of using API Gateway, I deployed the API using AWS Lambda Function URLs, which provided a simpler and more direct approach to serving HTTP requests.

Image description

What is the Number Classification API?

The Number Classification API is a FastAPI-based service that classifies numbers based on their mathematical properties. It can determine if a number is:

  • Prime
  • Armstrong
  • Perfect
  • Odd or even
  • Sum of its digits
  • Fun facts about the number (retrieved from an external API)

This API was designed to handle both positive and negative numbers, as well as floating-point inputs, which are converted to integers. see my GitHub Repo

Choosing AWS Lambda Function URL Over API Gateway

Initially, I considered deploying my FastAPI application using API Gateway and Lambda. However, I decided to use AWS Lambda Function URLs instead for the following reasons:

  • Simplicity: Lambda Function URLs provide a built-in HTTP endpoint, reducing the need for additional API Gateway configurations.
  • Direct Invocation: Function URLs allow direct access to the Lambda function without needing an API Gateway mapping.
  • Lower Cost: Since API Gateway incurs additional costs, using Lambda Function URLs helped reduce expenses.

Deployment Process

Here’s a step-by-step breakdown of how I deployed my FastAPI application on AWS Lambda:

1. Preparing the Deployment Package

To deploy a FastAPI application on AWS Lambda, it must be packaged correctly. I installed the necessary dependencies and zipped the application:

Compress-Archive venv\Lib\site-packages\* lambda.zip 
Compress-Archive .\main.py -Update lambda.zip
Enter fullscreen mode Exit fullscreen mode

2. Creating an AWS Lambda Function

  • Logged into the AWS Lambda console.
  • Created a new Lambda function using Python 3.9+ as the runtime.
  • Uploaded the lambda.zip file as the function’s code.

3. Enabling Lambda Function URL

  • Navigated to the Function URL section in the Lambda console.
  • Enabled the Function URL and set the authentication type to NONE to allow public access.
  • Copied the generated Function URL for testing.

4. Configuring CORS

Since the API was designed to be publicly accessible, I enabled CORS to allow requests from any origin. This was achieved by adding the CORSMiddleware in the FastAPI application:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Enter fullscreen mode Exit fullscreen mode

5. Testing the API

To ensure everything was working correctly, I tested the deployed API using curl and a web browser:

curl -X GET "https://your-lambda-function-url/api/classify-number?number=153"
Enter fullscreen mode Exit fullscreen mode

The response returned valid JSON data, confirming a successful deployment!

Challenges Faced

Deploying FastAPI on AWS Lambda wasn’t without its challenges. Some key issues I encountered included:

  1. Import Errors: Initially, I faced ImportModuleError: No module named 'pydantic_core._pydantic_core', which was due to package incompatibilities. Switching to an AWS-supported Python version and ensuring all dependencies were installed inside the Lambda layer resolved this issue.
  2. CORS Issues: The first few API requests were blocked due to missing CORS headers. Adding allow_origins=["*"] in CORSMiddleware fixed this.
  3. Number Validation Errors: The API initially returned 400 Bad Request for negative numbers and floating-point values. After refining the number validation logic, all valid numbers were correctly processed.

Key Takeaways

Deploying a FastAPI application using AWS Lambda Function URLs proved to be an efficient and cost-effective approach. Some important lessons I learned include:

  • AWS Lambda is powerful for lightweight APIs: It eliminates the need for managing infrastructure.
  • Function URLs simplify deployment: No need for API Gateway if a simple public endpoint is required.
  • Proper error handling is crucial: Ensuring valid JSON responses helps in debugging and API usability.
  • CORS must be configured properly: Without it, web applications may fail to make requests to the API.

Conclusion

This project was a great learning experience and a significant milestone in my cloud journey. It reinforced my understanding of AWS Lambda, FastAPI, and CORS configurations. As I progress in the HNG DevOps Internship, I look forward to tackling more complex deployments and optimizing API performance.

If you’re considering deploying a FastAPI service on AWS Lambda, I highly recommend trying Lambda Function URLs for their ease of use and cost efficiency!


What are your thoughts on this approach? Let’s discuss this in the comments! 🚀

Top comments (0)