Post

Building a Secure Password Generator API with AWS Lambda and API Gateway

End-to-end guide on creating a Python-based password generator, deploying it to AWS Lambda, exposing it securely via API Gateway, and applying security best practices.

Building a Secure Password Generator API with AWS Lambda and API Gateway

Password Generator API Project ๐Ÿ”โ˜๏ธ

In this project, weโ€™ll build a Python-based secure password generator, deploy it as an AWS Lambda function, and expose it through Amazon API Gateway.
This approach enables a fully serverless, stateless, and secure password generation service that can be used via HTTP calls.

Letโ€™s begin by understanding how the password generation logic works and how it ensures all security constraints are met.


1. Understanding the Password Generator Logic ๐Ÿงฉ

Hereโ€™s the core Python function that generates the passwords:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import re
import secrets
import string

def generate_password(length=16, nums=1, special_chars=1, uppercase=1, lowercase=1):
    letters = string.ascii_letters
    digits = string.digits
    symbols = string.punctuation
    all_characters = letters + digits + symbols

    constraints = [
        (nums, r'\d'),
        (special_chars, r'[!@#$%^&*(),.?":{}|<>]'),
        (uppercase, r'[A-Z]'),
        (lowercase, r'[a-z]')
    ]

    while True:
        password = ''.join(secrets.choice(all_characters) for _ in range(length))
        if all(constraint <= len(re.findall(pattern, password)) for constraint, pattern in constraints):
            return password

๐Ÿ” How It Works

  1. Character sets are defined (letters, digits, and symbols).
  2. Inside a while True loop, the function generates a random password using secrets.choice().
  3. After each generation, it checks every security constraint (regex-based).
  4. If all constraints are satisfied, it returns the password and breaks the loop.
  5. If not, the loop regenerates until a valid password is produced.

This ensures that no matter how the random selection behaves, the final password always meets all requirements.

  • Example output:
1
2
3

Xg@3wLp!q9H#sTzY

2. Creating the Lambda Function ๐Ÿง 

Now, letโ€™s turn our password generator into a Lambda function that can receive parameters from an HTTP request and return a generated password in JSON.

Lambda Function code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import json
from password_generator import generate_password

def lambda_handler(event, context):
    try:
        params = event.get("queryStringParameters", {}) or {}
        length = int(params.get("length", 16))
        nums = int(params.get("nums", 1))
        special_chars = int(params.get("special_chars", 1))
        uppercase = int(params.get("uppercase", 1))
        lowercase = int(params.get("lowercase", 1))

        password = generate_password(length, nums, special_chars, uppercase, lowercase)

        return {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps({"password": password})
        }

    except Exception as e:
        return {
            "statusCode": 400,
            "body": json.dumps({"error": str(e)})
        }

๐Ÿ—‚๏ธ Folder Structure

We will have our Lambda Function and Password Generator scripts in two separate .py files (as you can see we previously imported the password_generator into our lambda handler.)

1
2
lambda_function.py
password_generator.py

Files In Explorer

Then compress the folder for deployment:

1
zip -r lambda_function.zip lambda_function.py password_generator.py

Always include both scripts when uploading to Lambda.

3. Deploying to AWS Lambda โ˜๏ธ

  1. Go to the AWS Lambda Console โ†’ Create Function.
  2. Choose:
    • Runtime: Python 3.12
    • Architecture: x86_64
    • Permissions: attach AWSLambdaBasicExecutionRole

Creating Lambda Function

Creating IAM role

Selecting IAM Permissions

Selecting Created Role

  1. Upload your lambda_function.zip.

Upload Zip

Selecting Zip File

  1. Set handler:
    1
    
    lambda_function.lambda_handler
    

    Set Handler

  2. Save and Deploy.

You can now test it using the built-in Lambda test tool:

1
2
3
4
5
6
7
8
9
{
  "queryStringParameters": {
    "length": "20",
    "nums": "2",
    "special_chars": "2",
    "uppercase": "1",
    "lowercase": "1"
  }
}

Testing Lambda

4. Exposing the Function via API Gateway ๐ŸŒ

To allow external clients to access the Lambda securely:

  1. Open Amazon API Gateway โ†’ Create API โ†’ HTTP API.
  2. Add Integration โ†’ select your Lambda function.

Add Integration

Added Integration

  1. Create a GET method /generate-password.

Creating GET Method

  1. Deploy โ†’ copy your Invoke URL.

API Overview

Example request:

1
2
3
https://abcd1234.execute-api.eu-central-1.amazonaws.com/generate-password?length=20&nums=2&special_chars=2

Expected JSON response:

1
2
3
4
5

{
  "password": "T!k7Gp3Wz@9hQ2Lm"
}

API Gateway automatically uses HTTPS, making sure that all responses are encrypted in transit.

5. Adding Security and Validation ๐Ÿ”’

To maintain high security standards, i suggest you apply the following best practices:

โœ… Input Validation

  • Limit maximum password length (e.g., 64)
  • Validate integer types for all inputs

โœ… Logging and Monitoring

  • Enable CloudWatch Logs to track requests and errors
  • Monitor API calls and Lambda performance

โœ… Access Control

  • Add an API Key and attach it to a Usage Plan
  • Or integrate with AWS Cognito for authenticated access

โœ… Rate Limiting

Set throttling limits (e.g., 10 requests per second) in API Gateway to prevent brute-force abuse.

โœ… Secrets Management

If you want to extend the capabilites of the API to store the passwords, use AWS Secrets Manager โ€” never log or store passwords in plaintext.

The Lambda should only generate and return the password once; it must never persist it in any storage.

6. Full Architecture Overview ๐Ÿงฑ

Hereโ€™s the final flow of your system:

๐Ÿ—บ๏ธ Architecture Diagram

Full Diagram

ComponentDescription
LambdaExecutes password generation logic
API GatewayProvides HTTPS interface to Lambda
IAM RoleGrants execution and logging permissions
CloudWatchCollects metrics and logs for monitoring

7. Testing the API ๐Ÿงช

You can now test it via browser or curl:

1
2
3
curl "https://liwackcyc1.execute-api.us-east-1.amazonaws.com/generate-password?length=20&nums=2&special_chars=2"

Response:

1
2
3
4
5

{
  "password": "R@5mP!4dXt7kLz8s"
}

CURL Test

Each call generates a unique password that meets all defined constraints.

8. Optional Enhancements ๐Ÿš€

  • Add logging for validation errors
  • Implement Terraform for IaC automation
  • Add unit tests to validate regex constraints
  • Integrate CloudFront for caching or rate protection
  • Extend to Secrets Manager to deliver temporary credentials securely

9. Project Summary ๐Ÿงพ

LayerTechnologyPurpose
ApplicationPython 3.12Password generation logic
ComputeAWS LambdaServerless execution
API LayerAmazon API GatewaySecure HTTPS endpoint
MonitoringCloudWatchLogs and metrics
SecurityIAM + API KeysAccess control and encryption

This project demonstrates a real-world example of building secure, serverless utilities in AWS using simple Python logic โ€” lightweight, scalable, and safe by design.

๐Ÿง  Final Thoughts

By combining AWS Lambda, API Gateway, and Python, weโ€™ve built a serverless password generator API that enforces strong password rules while maintaining minimal attack surface. The best part โ€” it scales automatically and costs virtually nothing for occasional usage.

Serverless, secure, and simple โ€” just as it should be. ๐Ÿ”

This post is licensed under CC BY 4.0 by the author.