Search code examples
aws-lambda

colon not supported in rawQueryString event?


I have this lambda function and it works as expected.

import json

def lambda_handler(event,context):
  tempurl = event['rawQueryString']

  return {
        'statusCode': 200,
        'headers': { "content-type": "application/json; charset=utf-8" },
        'body': json.dumps(tempurl, ensure_ascii=False)
    }
    

This returns "test"

https://nu7xvoo6niguuqtkqs7qpp6zq0fnzlo.lambda-url.us-east-1.on.aws/?test

But this does not return the URL:

https://nu7xvoo6niguuqtkqs7qpp6zq0fnzlo.lambda-url.us-east-1.on.aws/?http://yahoo.com

returns: {"Message":null}

expected: http://yahoo.com

colon : and slash / does not seem to be supported in function URL 'rawQueryString' event?


Solution

  • The issue arises from the fact that the URL contains an illegal query string in the form of another URL (http://yahoo.com), which is not correctly encoded. In URLs, certain characters like slashes ("/") are reserved and should be properly percent-encoded when used as values in query parameters. In this case, "http://yahoo.com" should be percent-encoded to be a valid query parameter value.

    Assuming that you'd be calling this API from a browser-based application. You will have to use encodeURIComponent method to transform your URL into a legal query string.

    encodeURIComponent('http://yahoo.com')
    

    In your Lambda function, you’ll have to decode the encoded query string by using the following code:

    import urllib.parse
    import json
    
    def lambda_handler(event,context):
      tempurl = urllib.parse.unquote(event['rawQueryString'])
    
      return {
            'statusCode': 200,
            'headers': { "content-type": "application/json; charset=utf-8" },
            'body': json.dumps(tempurl, ensure_ascii=False)
        }