53
votes

In this question How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

shows how to map query string params to AWS lambda using API gateway. I would like to do the same but mapping POST values instead of query-string. I tried:

{
    "values": "$input.params()"
}

but did not work, I don't see the actual form data. BTW I am posting using:

application/x-www-form-urlencoded

I get my response from my lambda function, so I know it is invoking lambda fine, but my problem is that I don't see the POST params anywhere. I can;t figure out how to map them. I dump all I get on Lambda side and here it is:

 {"values":"{path={}, querystring={}, header={Accept=*/*, Accept-Encoding=gzip, deflate, Accept-Language=en-US,en;q=0.8, Cache-Control=no-cache, CloudFront-Forwarded-Proto=https, CloudFront-Is-Desktop-Viewer=true, CloudFront-Is-Mobile-Viewer=false, CloudFront-Is-SmartTV-Viewer=false, CloudFront-Is-Tablet-Viewer=false, CloudFront-Viewer-Country=US, Content-Type=application/x-www-form-urlencoded, Origin=chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop, Postman-Token=7ba28698-8753-fcb1-1f48-66750ce12ade, Via=1.1 6ba5553fa41dafcdc0e74d152f3a7a75.cloudfront.net (CloudFront), X-Amz-Cf-Id=sc8C7dLcW0BHYopztNYrnddC0hXyFdBzHv0O9aWU1gKhd1D_J2HF3w==, X-Forwarded-For=50.196.93.57, 54.239.140.62, X-Forwarded-Port=443, X-Forwarded-Proto=https}}"}
11
Take a look at this tutorial, I believe it will help - snowulf.com/2015/08/05/…Stefan

11 Answers

81
votes

Good answer by r7kamura. Additionally Here's an example of an understandable and robust mapping template for application/x-www-form-urlencoded that works for all cases (assuming POST):

{
    "data": {
        #foreach( $token in $input.path('$').split('&') )
            #set( $keyVal = $token.split('=') )
            #set( $keyValSize = $keyVal.size() )
            #if( $keyValSize >= 1 )
                #set( $key = $util.urlDecode($keyVal[0]) )
                #if( $keyValSize >= 2 )
                    #set( $val = $util.urlDecode($keyVal[1]) )
                #else
                    #set( $val = '' )
                #end
                "$key": "$val"#if($foreach.hasNext),#end
            #end
        #end
    }
}

It would transform an input of

name=Marcus&email=email%40example.com&message=

into

{
    "data": {
                "name": "Marcus",
                "email": "[email protected]",
                "message": ""
    }
}

A Lambda handler could use it like this (this one returns all input data):

module.exports.handler = function(event, context, cb) {
  return cb(null, {
    data: event.data
  });
};
22
votes

You can convert any request body data into valid JSON format by configuring the mapping templates in the integration settings so that AWS Lambda can receive it.

Currently it seems Amazon API Gateway does not support application/x-www-form-urlencoded officially yet, but avilewin posted a solution to do that on the AWS forums. In the mapping templates you can use Velocity Template Language (VTL), so what you need to do is to configure mapping templates that convert application/x-www-form-urlencoded format into valid JSON format. Of course this is a dirty solution, but I think it's the only way to do that for now.

22
votes

If you enable Lambda Proxy Integration enter image description here

The POST body will be available from:

event['body']['param']

GET parameters and headers will also be available via

event['pathParameters']['param1']
event["queryStringParameters"]['queryparam1']
event['requestContext']['identity']['userAgent']
event['requestContext']['identity']['sourceIP']
11
votes

You can convert the params into JSON with a API gateway template: https://forums.aws.amazon.com/thread.jspa?messageID=673012&tstart=0#673012

Or you may do this in the lambda function itself using QueryString parser pacakge: https://www.npmjs.com/package/qs

var qs = require('qs');
var obj = qs.parse('a=c');  // { a: 'c' } 

If Amazon adds built-in support for such feature, I will use that but until then I personally prefer the second way because it's cleaner and easier to debug if something goes wrong.

Update July 2017:

You may use proxy integration which supports it by default: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html

7
votes

Extending @markus-whybrow answer:

{
        #foreach( $token in $input.path('$').split('&') )
            #set( $keyVal = $token.split('=') )
            #set( $keyValSize = $keyVal.size() )
            #if( $keyValSize >= 1 )
                #set( $key = $util.urlDecode($keyVal[0]) )
                #if( $keyValSize >= 2 )
                    #set( $val = $util.urlDecode($keyVal[1]) )
                #else
                    #set( $val = '' )
                #end
                "$key": "$util.escapeJavaScript($val)"#if($foreach.hasNext),#end
            #end
        #end
    }

This gets rid of "data" and also fixes a case if you have a double-quote in one of your values.

4
votes

I implemented an API with POST requests where Content-Type was application/x-www-form-urlencoded. If you're just interested in getting a long querystring of values similar to GET requests, then use this mapping syntax.

{
    "body": "$input.body"
}

Note, you can add other mappings too... I left that out to address the original problem.

Here's a blog tutorial that I used when originally implementing my API. My lambda function then parses the querystring passes the data onto other processes.

4
votes

I found a really simple solution I think it is worth to share, since it took me a few time to find this minimal working code.

If you have a common form, that send data with content type application/x-www-form-urlencoded, just flag "Lambda proxy integration", then you will find encoded form data in event.body which can be parsed with Node.js querystring native module.

const querystring = require('querystring')

function handler (event, context, callback) {
  // Read form data.
  const { user, pass } = querystring.parse(event.body)

  // Follows your code to handle request.
}
3
votes

This works with lambda integration. Assuming your POST request body is e.g.

{
   "name" : "Hello",
   "address" : "Cool place" 
}

You can access it like so :

if (event.body !== null && event.body !== undefined) {
   let body = JSON.parse(event.body)
   let name = body.name;
   let address = body.address;
}

More info here : http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html

1
votes

Simple function that returns ordered dictionary of posted values:

import urllib
from collections import OrderedDict
postdata = ''

def GetPostData(body):
    #postdata = OrderedDict()
    postdata = {}
    for items in body.split('&'):
        vals = items.split('=')
        postdata[vals[0]] = urllib.parse.unquote(vals[1])
    return postdata

#Testing it out:
#Assume you get body from event['body'] or body = event.get['body']
body = 'text=This%20works%20really%20well%21%245123%21%403%2146t5%40%2341&anotherkey=isawesome23412%201%21%403%21%40312'

postdata = GetPostData(body)
print(postdata['text'])
#returns 'This works really well!$5123!@3!46t5@#41'
print(postdata['anotherkey'])
#returns 'isawesome23412 1!@3!@312'

To avoid a key error when a posted items is missing, you should use value = postdata.get('') instead, as value will be None if the key is not present.

1
votes

If you want to send to your Lambda function all the body from POST, write this at Integration Request:

{
    "values": $input.json('$')
}

If you want to build your own structure from the body, do this:

{
    "values": {
        "body-param1": $input.json('body-param1'),
        "others": {
            "body-param2": "$input.json('body-param2')",
        }
    }
}

Where body-param1 is a number and body-param2 is a string.

If your want to send the headers, do this:

{
    "headers": {
        #foreach($param in $input.params().header.keySet())
            "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext), #end
        #end
    }
}
0
votes

June 2021

Mapping template for application/x-www-form-urlencoded for POST: (Python)

from base64 import b64decode
from urllib.parse import parse_qs

def lambda_handler(event, context):
    params = parse_qs(b64decode(event.get('body')).decode('utf-8'))
    print(params.get('name')[0])
    print(params.get('email')[0])

Similarly, do whatever operations you want to perform using params dictionary and whatever is the parameter name.