Ends in
00
days
00
hrs
00
mins
00
secs
ENROLL NOW

⏳ Bonus Deal: $3 Off All Products, $1.99 eBooks, 25% Bundle Discounts & CodeQuest AI Labs Access!

Why I Chose AWS Lambda to Power My App’s Cloud Logic

Home » AWS Lambda » Why I Chose AWS Lambda to Power My App’s Cloud Logic

Why I Chose AWS Lambda to Power My App’s Cloud Logic

Last updated on June 27, 2025

For this article, I will demonstrate how I used AWS Lambda as an all-around backend system for a mock-up mobile application I developed for my Design subject in school. The mobile application is an IoT application that integrates communication between a mobile device and a handheld barcode scanner using a Bluetooth module. It also includes security functions, such as code decryption and user statuses. For the dependencies, I used flutter_blue, get, and http.

The list below indicates the use cases of AWS Lambda for my mobile application. I hope, by the end of this article, you will know how to use AWS Lambda for the following purposes:

  1. Authentication
  2. Database
  3. Decryptor

Without further ado, let us dive deep into the implementation processes:

AUTHENTICATION

For the authentication, the mobile application intends to have a couple of users with different statuses, such as “Ready” and “Not Ready.” Here is how I implemented it:

Tutorials dojo strip

lambda_function.py:

def get_mock_users():
    return [
        {"username": "user1", "password": "pass123", "bazaar_ready": True, "key": "abc123xyz"},
        {"username": "demo", "password": "demo123", "bazaar_ready": False, "key": None},
        {"username": "admin", "password": "adminpass", "bazaar_ready": True, "key": "InputKey"},
    ]

def lambda_handler(event, context):
    try:
        body = json.loads(event.get("body", "{}"))
        
        if "username" in body and "password" in body:
            username = body["username"]
            password = body["password"]
            users = get_mock_users()

            user = next((u for u in users if u["username"] == username and u["password"] == password), None)
            if not user:
                return {
                    'statusCode': 401,
                    'body': json.dumps({'error': 'Invalid username or password'})
                }
            return {
                'statusCode': 200,
                'body': json.dumps({
                    'username': user['username'],
                    'bazaar_ready': user['bazaar_ready'],
                    'key': user['key']
                })
            }

login_page.dart: 

Future login() async {
    final url = Uri.parse(
        'https://your-aws-lambda-url.lambda-url.us-east-1.on.aws/'); // Replace with your Lambda endpoint
    final response = await http.post(
      url,
      body: jsonEncode({
        'username': _usernameController.text.trim(),
        'password': _passwordController.text,
      }),
      headers: {'Content-Type': 'application/json'},
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      if (data['bazaar_ready'] == true) {
        globalBazaarKey = data['key'];
        Get.off(() => const MyHomePage());
        print(globalBazaarKey);
      } else {
        showDialog(
          context: context,
          builder: (_) => AlertDialog(
            title: const Text("Access Denied"),
            content: const Text("Your account is not ready for Bazaar access."),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text("OK"),
              ),
            ],
          ),
        );
      }
    } else {
      showDialog(
        context: context,
        builder: (_) => AlertDialog(
          title: const Text("Login Failed"),
          content: const Text("Invalid username or password."),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text("OK"),
            ),
          ],
        ),
      );
    }
  }

This simple login function manages the user’s access to the app, ensuring security and compliance within the user base.

DATABASE

Next, I will describe how I used AWS Lambda for a mock-up database for my mobile application. The application will store product

details, such as barcodes, prices, and product names for context. Here is how I implemented it:

def get_mock_data():
    return [
        {"uuid": "890123456712", "product_name": "Classic Taho", "image_link": "https://images.deliveryhero.io/image/fd-ph/Products/30704146.jpg", "rating": "4.5", "price": "200.00"},
        {"uuid": "890123456736", "product_name": "Brown Sugar Taho", "image_link": "https://images.deliveryhero.io/image/fd-ph/Products/15746025.jpg", "rating": "4", "price": "220.00"},
]

In the actual lambda function, the mock_data() has more than two items. For simplicity, I only included two items to avoid prolonging

the implementation process.

DECRYPTION

Lastly, for the decryption process. This part of the lambda function ensures security and avoids data breaches, as the barcodes/UUIDs

are designed to be transmitted encrypted. The lambda function handles the decryption of these barcodes or UUIDs

to be displayed on the mobile app. Here is how I implemented it:

def xor_decrypt_from_hex(encrypted_hex, key):
    # Step 1: Convert hex string to bytes
    encrypted_bytes = bytes.fromhex(encrypted_hex)

    # Step 2: XOR each byte with key
    decrypted_chars = []
    key_bytes = key.encode()

    for i in range(len(encrypted_bytes)):
        decrypted_char = encrypted_bytes[i] ^ key_bytes[i % len(key_bytes)]
        decrypted_chars.append(chr(decrypted_char))

    # Step 3: Join decrypted characters to form the original string
    return ''.join(decrypted_chars)

# Decryption
        uuid = xor_decrypt_from_hex(uuid, xor_key)

        print(f"Decrypted text: {uuid}")


        mock_data = get_mock_data()
        product = next((item for item in mock_data if item["uuid"] == uuid), None)
        
        if not product:
            return {
                'statusCode': 404,
                'body': json.dumps({'error': 'Product not found'})
            }
        
        return {
            'statusCode': 200,
            'body': json.dumps(product)
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }

In Flutter:

 Future<Map<String, dynamic>?> fetchProductDetails(String uuid) async {
    try {
      final storedKey = globalBazaarKey;

      if (storedKey == null || storedKey.isEmpty) {
        Get.snackbar("Error", "User key not found. Please log in again.");
        return null;
      }

      final requestBody = {
        'uuid': uuid,
        'key': storedKey,
      };

      print("Sending payload: $requestBody");

      final response = await http.post(
        Uri.parse(
            "https://your-aws-lambda-url.lambda-url.us-east-1.on.aws/"),
        headers: {'Content-Type': 'application/json'},
        body: json.encode(requestBody),
      );

      print("API response: ${response.body}");

      if (response.statusCode == 200) {
        return json.decode(response.body) as Map<String, dynamic>;
      } else {
        Get.snackbar("Error", "Failed to fetch product details.");
        return null;
      }
    } catch (e) {
      Get.snackbar("Network Error", "Please check your internet connection.");
      return null;
    }
  }

Here is the entirety of the AWS Lambda Function:

import json
from itertools import cycle

def get_mock_users():
    return [
        {"username": "user1", "password": "pass123", "bazaar_ready": True, "key": "abc123xyz"},
        {"username": "demo", "password": "demo123", "bazaar_ready": False, "key": None},
        {"username": "admin", "password": "adminpass", "bazaar_ready": True, "key": "InputKey"},
    ]

def xor_decrypt_from_hex(encrypted_hex, key):
    # Step 1: Convert hex string to bytes
    encrypted_bytes = bytes.fromhex(encrypted_hex)

    # Step 2: XOR each byte with key
    decrypted_chars = []
    key_bytes = key.encode()

    for i in range(len(encrypted_bytes)):
        decrypted_char = encrypted_bytes[i] ^ key_bytes[i % len(key_bytes)]
        decrypted_chars.append(chr(decrypted_char))

    # Step 3: Join decrypted characters to form the original string
    return ''.join(decrypted_chars)

# Example usage:

def get_mock_data():
    return [
        {"uuid": "890123456712", "product_name": "Classic Taho", "image_link": "https://images.deliveryhero.io/image/fd-ph/Products/30704146.jpg", "rating": "4.5", "price": "200.00"},
        {"uuid": "890123456736", "product_name": "Brown Sugar Taho", "image_link": "https://images.deliveryhero.io/image/fd-ph/Products/15746025.jpg", "rating": "4", "price": "220.00"},
    ]

def lambda_handler(event, context):
    try:
        body = json.loads(event.get("body", "{}"))
        
        if "username" in body and "password" in body:
            username = body["username"]
            password = body["password"]
            users = get_mock_users()

            user = next((u for u in users if u["username"] == username and u["password"] == password), None)
            if not user:
                return {
                    'statusCode': 401,
                    'body': json.dumps({'error': 'Invalid username or password'})
                }
            return {
                'statusCode': 200,
                'body': json.dumps({
                    'username': user['username'],
                    'bazaar_ready': user['bazaar_ready'],
                    'key': user['key']
                })
            }
        
        uuid = body.get("uuid")
        xor_key = body.get("key")
        print(f"Received UUID: {uuid}")
        print(f"Received Key: {xor_key}")
        
        if not uuid:
            return {
                'statusCode': 400,
                'body': json.dumps({'error': 'UUID is required'})
            }
        
        if not xor_key:
            return {
                'statusCode': 400,
                'body': json.dumps({'error': 'Key is required'})
            }
        
        # Decryption
        uuid = xor_decrypt_from_hex(uuid, xor_key)

        print(f"Decrypted text: {uuid}")


        mock_data = get_mock_data()
        product = next((item for item in mock_data if item["uuid"] == uuid), None)
        
        if not product:
            return {
                'statusCode': 404,
                'body': json.dumps({'error': 'Product not found'})
            }
        
        return {
            'statusCode': 200,
            'body': json.dumps(product)
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }

Conclusion

AWS Lambda again proves why it is one of the most versatile AWS products. From a single lambda function, we were able to provide

our application with a decent backend architecture complete with authentication, database, and decryption security features. However,

I would suggest that we add other AWS products to the mix, such as RDS and Cognito. Nevertheless, we were able to come up with a

full-functioning mobile application that only used one AWS product: AWS Lambda.

References

Free AWS Courses

⏳ Bonus Deal: $3 Off All Products, $1.99 eBooks, 25% Bundle Discounts & CodeQuest AI Labs Access!

Tutorials Dojo portal

Learn AWS with our PlayCloud Hands-On Labs

🧑‍💻 CodeQuest – AI-Powered Programming Labs

FREE AI and AWS Digital Courses

Tutorials Dojo Exam Study Guide eBooks

tutorials dojo study guide eBook

FREE AWS, Azure, GCP Practice Test Samplers

Subscribe to our YouTube Channel

Tutorials Dojo YouTube Channel

Join Data Engineering Pilipinas – Connect, Learn, and Grow!

Data-Engineering-PH

K8SUG

Follow Us On Linkedin

Recent Posts

Written by: Marc Hendri Soquiat

Marc Hendri Soquiat, aka "Soki." is an AWS Certified Cloud Practitioner and an Intern at Tutorials Dojo. Soki is a hardworking and dedicated individual eager to learn new tech, explore different fields, and be where opportunity is.

AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!

Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!

View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses

Our Community

~98%
passing rate
Around 95-98% of our students pass the AWS Certification exams after training with our courses.
200k+
students
Over 200k enrollees choose Tutorials Dojo in preparing for their AWS Certification exams.
~4.8
ratings
Our courses are highly rated by our enrollees from all over the world.

What our students say about us?