Search code examples
aws-lambda

Unicode characters in function URL


I have this lambda function that works as expected:

import json

def lambda_handler(event, context):
    message = 'Hello {} !'.format(event['rawQueryString'])
    return { 
        'message' : message
    }

I get a function URL like this...

https://2ku5vw336655hiomtcogv4sopm0bpqdo.lambda-url.us-east-1.on.aws/?world

And it returns:

{"message":"Hello world !"}


The only problem is that unicode characters are not processed correctly in URL. For e.g.

https://2ku5vw336655hiomtcogv4sopm0bpqdo.lambda-url.us-east-1.on.aws/?भारत

does not return:

{"message":"Hello भारत !"}

It returns:

{"message":"Hello %E0%A4%AD%E0%A4%BE%E0%A4%B0%E0%A4%A4 !"}

How do I return the correct unicode characters in Lambda?


I tried this, but the same results:

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

Solution

  • you can use urllib.parse.unquote to decode URL-encoded strings , for your reference check this https://docs.python.org/3/library/urllib.parse.html

    import json
    import urllib.parse
    
    def lambda_handler(event, context):
        raw_query_string = event['rawQueryString']
        print("raw",raw_query_string)
        decoded_query_string = urllib.parse.unquote(raw_query_string)
        print("dec",decoded_query_string)
        message = 'Hello {} !'.format(decoded_query_string)
        
        response = {
            'message': message
        }
        
        return {
            'statusCode': 200,
            'headers': { "content-type": "application/json; charset=utf-8" },
            'body': json.dumps(response, ensure_ascii=False)
        }