AWS Lambda Not Getting Query Parameters - aws-lambda

I am setting up my first Lambda function on AWS. I use Python 3.6. My code is as follows:
def lambda_handler(event, context):
result = {}
result["Log stream name:"] = context.log_stream_name
result["Log group name:"] = context.log_group_name
result["Request ID:"] = context.aws_request_id
result["Mem. limits(MB)"] = context.memory_limit_in_mb
result["size of event"] = len(event)
result["type of event"] = str(type(event))
return result
I also set up an API Gateway for test Lambda.
However, no matter what query paramters I pass in to the API Gateway, the event is always an empty dict. Below is a sample response. What am I missing?
Request: /test/number?input=5
Status: 200
Latency: 223 ms
Response Body
{
"Log stream name:": "2018/12/05/[$LATEST]9d9fd5dd157046b4a67792aa49f5d71c",
"Log group name:": "/aws/lambda/test",
"Request ID:": "dce7beaf-f8c9-11e8-9cc4-85afb50a0e0c",
"Mem. limits(MB)": "128",
"size of event": 0,
"type of event": "<class 'dict'>"
}

Assuming you don't have request mapping templates, you should turn Lambda Proxy integration on.

Related

Capture details from http request and response in jmeter

I am setting up a jmeter test plan for http requests and I want to create a table capturing some details from http request and response. I read http request from a file using CSV Data Set Config. My request and response formats are as follows
Http Request Format: {"TYPE":"<type>", "PAYLOAD": [<Array of data>]}
Http Response Format: {"RESPONSE":[<Array of data>]}
Things I want to capture for each request, response are TYPE from HTTP Request, Array Size of RESPONSE (or Array size of PAYLOAD) and Time Taken.
The jmeter version I am using is v5.2.1. Any inputs on how can I set this up?
Edit: My HTTP request is a POST request. I am looking to capture details from Request Body.
If you don't mind using JMeter Plugins you can:
Declare the variables from the CSV file as Sample Variables
Extract the number of matches from the response using JSON Extractor configured like:
Name of created variables: responsarray
JSON Path expressions: $.RESPONSE.*
Match Nr.: -1
the variable value you need to declare in the Sample Variables will be responsearray_matchNr
The above Sample Variables can be saved into a file using Flexible File Writer
If you cannot use the plugin you still can achieve the same using JSR223 Listener and the following Groovy code:
def result = new File('result.txt')
def request = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue())
def requestType = request.TYPE
def requestArray = request.PAYLOAD.size()
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def responseArray = response.RESPONSE.size()
def timeTaken = prev.getTime()
result << requestType << ',' << requestArray << ',' << responseArray << ',' << timeTaken << System.getProperty('line.separator')

ResourceNotFoundException while adding data to Kinesis Firehose stream using Lambda

I am trying to add data to Kinesis Firehose delivery stream using putrecord with python3.6 on aws lambda. When calling put record on the stream I get following exception.
An error occurred (ResourceNotFoundException) when calling the PutRecord operation: Stream MyStream under account 123456 not found.
I am executing following python code to add data to Stream.
import boto3
import json
def lambda_handler(event, context):
session = boto3.Session(aws_access_key_id=key_id, aws_secret_access_key=access_key)
kinesis_client = session.client('kinesis', region_name='ap-south-1')
records = event['Records']
write_records = list()
count = 0
for record in records:
count += 1
if str(record['eventName']).lower() == 'insert':
rec = record['dynamodb']['Keys']
rec.update(record['dynamodb']['NewImage'])
new_record = dict()
new_record['Data'] = json.dumps(rec).encode()
new_record['PartitionKey'] = 'PartitionKey'+str(count)
# Following Line throws Exception
kinesis_client.put_record(StreamName="MyStream", Data=new_record['Data'], PartitionKey='PartitionKey'+str(count))
elif str(record['eventName']).lower() == 'modify':
pass
write_records = json.dumps(write_records)
print(stream_data)
MyStream status is active and source for the stream data is set to Direct PUT and other sources
If you are sure that the stream name is correct, you can create client with regional endpoint of Kinesis
kinesis_client = session.client('kinesis', region_name='ap-south-1', endpoint_url='https://kinesis.ap-south-1.amazonaws.com/')
AWS Service Endpoints List
https://docs.aws.amazon.com/general/latest/gr/rande.html
Hope this helps !!!

jmeter: evaluate the values of JSON values

I am trying to test my API response using JSON assertion in JMeter, but couldn't find out on how to achieve it. The API returns 2 values, and I need to check if the difference between these two value are consistent
API response:
{
"start": "12759898",
"end": "12759907"
}
I've tried like the above, but it seems to be wrong, as its a JSONPath variable.
Could anyone guide on how to evaluate these values? is it possible to achieve this?
It looks like a job for JSR223 Assertion
Add JSR223 Assertion as a child of the request which returns the above JSON
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def start = response.start as long
def end = response.end as long
def delta = end - start
if (delta != 10) {
AssertionResult.setFailure(true)
AssertionResult.setFailureMessage('Expected: 10, got: ' + delta)
}
If the difference between start and end will not be equal to 10 - the request will be marked as failed.
More information:
Groovy: Parsing and producing JSON
Scripting JMeter Assertions in Groovy - A Tutorial

AWS Lambda Chalice: "The request could not be satisfied" Error

I want my lambda function to return the response of another lambda function invoked via AWS API Gateway.
Both functions are deployed by Lambda Chalice to different APIs.
When the first function sends a request to the 2nd functions API endpoint, I am getting an error response saying that "The request could not be satisfied".
Any help is appreciated.
Edit to include some code as requested; shortened for brevity:
#app.route('/verify_user_token', methods=['GET'], cors=True)
def verify_user_token():
request = app.current_request
params = request.query_params or {}
# do your things here; if all goes well:
r = requests.get(ANOTHER_AWS_API_GATEWAY_ENDPOINT_URL, data=params)
return r.text

Parsing the response using REST vs. SOAP API in Ruby

I am trying to parse a response that I receive using Rest API calls, but get an error when I say, something like: response.body.first[1]. I am transferring Soap API calls to rest API calls. Is response.first something that can only be used in Soap, if so what is the equivalent in Rest? Here is the code snippet that I am having trouble with:
url = ##rest_base_url.to_s + "filters/#{id.to_s}/results"
resource = RestClient::Resource.new url, #username, #password
response = resource.get
data = JSON.parse(response.body)["data"]
if response.body.first[1][:return].nil?
requirements = nil
elsif response.body.first[1][:return].is_a?(Array)
# puts "|get_requirements| req is an array".blue
requirements = []
Thank you

Resources