7

I am trying to integrate API gateway with Lambda proxy,

The API server receives the request with these parameters i.e postcode and house

https://api.domain.com/getAddressproxy?postcode=XX2YZ&house=123

However tests from the API gateway to the Lambda proxy does not return values

https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/Test/getaddressproxy?postcode=XX2YZ&house=123

I think the issue is that the lambda function is not passing the query string parameters to the API server.

Any idea how i can pass the query string parameters to the request object?

Code:

from __future__ import print_function

import json
import urllib2
import ssl

print('Loading function')

target_server = "https://api.domain.com"

def lambda_handler(event, context):
    print("Got event\n" + json.dumps(event, indent=2))

    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    print("Event here: ")
    print(event['path'])
    print(event["queryStringParameters"])

    req = urllib2.Request(target_server + event['path'])

    if event['body']:
        req.add_data(event['body'])

    # Copy only some headers
    copy_headers = ('Accept', 'Content-Type')

    for h in copy_headers:
        if h in event['headers']:
            req.add_header(h, event['headers'][h])

    out = {}

    try:
        resp = urllib2.urlopen(req, context=ctx)
        out['statusCode'] = resp.getcode()
        out['body'] = resp.read()

    except urllib2.HTTPError as e:

        out['statusCode'] = e.getcode()
        out['body'] = e.read()

    return out

2 Answers 2

8

Either you can take query string inside Lambda like below,

var result =  event["queryStringParameters"]['queryStringParam1']

According to your API URL,

var postcode =  event["queryStringParameters"]['postcode']
var house =  event["queryStringParameters"]['house']

or you can use body mapping template in the integration request section and get request body and query strings. Construct a new JSON at body mapping template, which will have data from request body and query string. As we are adding body mapping template your business logic will get the JSON we have constructed at body mapping template.

Inside body mapping template to get query string please do ,

$input.params('querystringkey')

For example inside body mapping template,

#set($inputRoot = $input.path('$'))
{
"firstName" : "$input.path('$.firstName')",
"lastName" : "$input.path('$.lastName')"
"language" : "$input.params('$.language')"
}

Please read https://aws.amazon.com/blogs/compute/tag/mapping-templates/ for more details on body mapping template

Sign up to request clarification or add additional context in comments.

3 Comments

i am using Lambda integration in API gateway, so i dont get the option to create a body mapping template, any other ideas?
@krisdigitx body mapping template you can do it API gateway only. Please have a look on the URL I have shared
Alternatively you can directly take it from code. I have updated the answer
6

event["queryStringParameters"] is a dictionary if the API Gateway passes one or None if not passed. Convert this to a query string and append to the Request URL.

...
import urllib
...

qs = urllib.urlencode(event["queryStringParameters"] or {})
req = urllib2.Request(
        ''.join(
          (target_server, event['path'], '?', qs)
        )
      )

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.