3

I want to read the "key" parameter of a http post request but it is not working.

def my_handler(event, context):
    print(event)
    print(event['body'])
    print("key: " + event['key'])

    key = event['query']['key']

    encoded_string = str(key).encode("utf-8")
    # Create the file named for example "42.json" containing the appropriate data
    s3_path =  str(key) + '.json'
    s3 = boto3.resource("s3")
    s3.Bucket(BUCKET_NAME).put_object(Key=s3_path, Body=encoded_string)

    message = {
       'message': 'Created {}!'.format(key)  
    }
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(message)
    }

Update: If I use the code below, I can read JSON data in an http post but I still cannot read form-data.

def my_handler(event, context):
    print(event)
    print(event['body'])
   # print("key: " + event['key'])
    print("key  " + json.loads(event['body'])["key"])

    key = json.loads(event['body'])["key"]

    encoded_string = str(key).encode("utf-8")
    # Create the file named for example "42.json" containing the appropriate data
    s3_path =  str(key) + '.json'
    s3 = boto3.resource("s3")
    s3.Bucket(BUCKET_NAME).put_object(Key=s3_path, Body=encoded_string)

    message = {
       'message': 'Created {}!'.format(key)  
    }
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(message)
    }

2 Answers 2

11

I had trouble with this too. I'm specifically working on an AWS Lambda using python3.7. Took a day, but I figured it out.

This code parses the "multipart/form-data" body into a dict called form_data. There are two notes: (a) This code makes an assumption that the post body and headers are utf-8 encoded; that seems to be particular to the AWS API Gateway, but I didn't do any due diligence to test that this holds for all cases. (b) Because the form could have multiple values for any field, the value for any key is a list. You were asking about retrieving "key" from the form data. If there's a single value for "key" then you'd reference form_data['key'][0].

import cgi
import io

def handler(event, context):
    print(event)
    print(event['body'])

    fp = io.BytesIO(event['body'].encode('utf-8'))
    pdict = cgi.parse_header(event['headers']['Content-Type'])[1]
    if 'boundary' in pdict:
        pdict['boundary'] = pdict['boundary'].encode('utf-8')
    pdict['CONTENT-LENGTH'] = len(event['body'])
    form_data = cgi.parse_multipart(fp, pdict)
    print('form_data=', form_data)
Sign up to request clarification or add additional context in comments.

9 Comments

This works, thank you, but you forgot to 'import io'
direct useful !
It is very useful !
@bonafidejed how can I read file from form_data variable. open() does not work
@MohsinSaeed that’s a different question altogether. I recommend posting that separately with the code and the error. If you mention me in a comment on that post I’ll take a look.
|
0

enter image description here 1. I presume that you are using API Gateway then its worth using Lambda proxy integration which is under your Integration requests on your API Gateway. aws docs

  1. IF you use this setting you don't need any mappings to be done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.