How to pass event info from aws API Gateway get to Lambda? - amazon-web-services

How do I refer to API Gateway GET query string parameters in a Lambda function ?
When I test I can use my local test event with "username": "larry"
When I test with a post I can use the body parameters as the event with "username": "larry"
With a get request, I don't have a body. How could I use query string parameters and then refer to them in the request. What event or other attribute do I use to get at the query param or what setting or change do I need to make?
Method request
Integration request
Query String
When testing I've referred to event["username", what do I do for an API request passing it as a query string parameter?

Login and click to API gateway and click on method - GET method
Go to Method Execution - select URL Query String Parameter and add query String parameter username
Now go to Integration Request tab Choose Body Mapping Template,
"content type application/json"
Generate Template like below
{
"username": "$input.params('username')"
}
Now write ;ambda which accept key value in pair .
module.exports.get = (event, context, callback) => {
const { username } = event.pathParameters;
console.log("username", username);
}
Now go and deploy your api on apigetway and find url and hit in browser example
https://xxx.yyy-api.us-east-2.amazonaws.com/prod/username?vaquarkhan
Hope it will help
https://docs.aws.amazon.com/de_de/apigateway/latest/developerguide/welcome.html
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-set-up-lambda-proxy-integration-on-proxy-resource

Related

Postman Mock Server matching algorithm logic for request body param form-data

Is there any option to send mock results depends on form data body value in postman?
I am sending some value in the body as form data and I have two example result and now the mock API return only one example I need to get the result based on the form data value from two examples
I have to call 2 Request with different body values(as form-data) and I need to return json array if the values are correct else I need to return a json object I have saved this two result but while I making mock API it is all ways sending now result only there is no changes in url
Is that possible to send response based on form-data in postman mock api?
I have an api example https://api.exmple.com and i am sending post request wit body form-data and filed check:false or check:true and i need to respond two json based on input filed check false or true how to do it?
When we do with get parameter it is working but not working with body form-data
Updates
I added this in header x-mock-match-request-body:true
Post man responding with this error message
{
"error": {
"name": "mockRequestNotFoundError",
"message": "Double check your method and the request path and try again.",
"header": "No matching requests"
}
}
Update I added postman api key but is not working but when i add x-mock-response-name it is working but i need to x-mock-match-request-body only

How to pass a path parameter in API gateway to invoke lambda function?

I need to pass a path param in the API.
By using the mapping template, I am able to pass query params and use them in the function.
Mapping template:
{
"Id": "$input.params('Id')" //this works fine after passing params as <url>?param=vale
}
With reference to this I created the mapping template as following-
{
"Id": "$input.params().querystring.get('Id')" // requirement is to be able to use <url>/value
}
I tried using 'Method request template' under genrate template, but it didn't work either.
When I invoke the URL urlname.execute-api.us-east-2.amazonaws.com/stag/functionname, it gives the value as undefined.
This is how I'm using the param:
class Lambda {
static run(event, context, callback) {
callback(null, 'Id '+ event.Id);
}
}
module.exports = Lambda;
Also, please tell me how to use those params in code.
Be kind :)
In order to be able to use <url>/value and get value from event follow this (Tested):
Configure your API gateway resource
Under /api2/{id} - GET - Integration Request configure your Mapping Templates
Execute request https://123456.execute-api.my-region.amazonaws.com/stage/api2/123
Lambda
console.log(event.id)
callback(null, {
id:event.id
});
CloudWatch
Hope this helps

How do I map path parameters from an API Gateway API to the Request Object of a Java Lambda

I have a lambda, written in Java, that accepts a Request Object of the structure
{
"id": "be1c320a-144f-464d-b32c-38ec7fb4445b",
"userId": "foobar"
}
When I call this Lambda through the test interface with such an object, it works fine.
I want to create an API where a GET request to
/users/foobar/items/be1c320a-144f-464d-b32c-38ec7fb4445b
i.e. of the form
/users/{userId}/items/{id}
calls this Lambda.
I have created the API resources /users, {userId}, items, and {id} appropriately.
And I have created the GET method (on /users/{userId}/items/{id})and associated it to the lambda.
When I test the API, it invokes the lambda, but with null values in the request. I can see it package the path as {"id":"be1c320a-144f-464d-b32c-38ec7fb4445b","userId": "foobar"} in the logs, but that's not being sent in the body.
I have tried creating a template map (and have tried RTFM), but cannot see how to map path parameters to a body.
How do I achieve this mapping?
I think your Request Object structure may not be properly configured. There may be a few ways to configure this. Here is some information that has helped me.
How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway - Demonstrates this mapping (albeit with python). However, taking the top response, if you enable "Use Lambda Proxy integration", you can similarily do this with Java as so:
#Override
public Object handleRequest(APIGatewayProxyRequestEvent input, Context context) {
Map<String, String> pathParameters = input.getPathParameters();
String id = pathParameters.get("id");
String userId = pathParameters.get("userId");
// Handle rest of request..
}
This is a tuturial using the serverless framework to create an Api with Java. This tutorial similarily accesses the pathParameters by parsing the input rather than using the APIGatewayProxyRequestEvent java class.
#Override
public Object handleRequest(Map<String, Object> input, Context context) {
try {
// get the 'pathParameters' from input
Map<String,String> pathParameters = (Map<String,String>)input.get("pathParameters");
String id = pathParameters.get("id");
String userId = pathParameters.get("userId");
} catch (Exception ex) {
logger.error("Error in retrieving product: " + ex);
}
}
Use a mapping template.
First, in the Method Request section, you should see userId and id as Request Paths
Then, in the Integration Request, do not choose Proxy Integration.
Then in the Mapping Templates section, add a new mapping template for application/json of the form
{
"id" : "$method.request.path.id",
"userId" : "$method.request.path.user_id"
}

How to get the HTTP method in AWS Lambda?

In an AWS Lambda code, how can I get the HTTP method (e.g. GET, POST...) of an HTTP request coming from the AWS Gateway API?
I understand from the documentation that context.httpMethod is the solution for that.
However, I cannot manage to make it work.
For instance, when I try to add the following 3 lines:
if (context.httpMethod) {
console.log('HTTP method:', context.httpMethod)
}
into the AWS sample code of the "microservice-http-endpoint" blueprint as follows:
exports.handler = function(event, context) {
if (context.httpMethod) {
console.log('HTTP method:', context.httpMethod)
}
console.log('Received event:', JSON.stringify(event, null, 2));
// For clarity, I have removed the remaining part of the sample
// provided by AWS, which works well, for instance when triggered
// with Postman through the API Gateway as an intermediary.
};
I never have anything in the log because httpMethod is always empty.
The context.httpMethod approach works only in templates. So, if you want to have access to the HTTP method in your Lambda function, you need to find the method in the API Gateway (e.g. GET), go to the Integration Request section, click on Mapping Templates, and add a new mapping template for application/json. Then, select the application/json and select Mapping Template and in the edit box enter something like:
{
"http_method": "$context.httpMethod"
}
Then, when your Lambda function is called, you should see a new attribute in the event passed in called http_method which contains the HTTP method used to invoke the function.
API Gateway now has a built-in mapping template that passes along stuff like http method, route, and a lot more. I can't embed because I don't have enough points, but you get the idea.
Here is a screenshot of how you add it in the API Gateway console:
To get there navigate to AWS Console > API Gateway > (select a resource, IE - GET /home) > Integration Request > Mapping Templates > Then click on application/json and select Method Request Passthrough from dropdown shown in the screenshot above
I had this problem when I created a template microservice-http-endpoint-python project from functions.
Since it creates an HTTP API Gateway, and only REST APIs have Mapping template I was not able to put this work. Only changing the code of Lambda.
Basically, the code does the same, but I am not using the event['httpMethod']
Please check this:
import boto3
import json
print('Loading function')
dynamo = boto3.client('dynamodb')
def respond(err, res=None):
return {
'statusCode': '400' if err else '200',
'body': err.message if err else json.dumps(res),
'headers': {
'Content-Type': 'application/json',
},
}
def lambda_handler(event, context):
'''Demonstrates a simple HTTP endpoint using API Gateway. You have full
access to the request and response payload, including headers and
status code.
To scan a DynamoDB table, make a GET request with the TableName as a
query string parameter. To put, update, or delete an item, make a POST,
PUT, or DELETE request respectively, passing in the payload to the
DynamoDB API as a JSON body.
'''
print("Received event: " + json.dumps(event, indent=2))
operations = {
'DELETE': lambda dynamo, x: dynamo.delete_item(**x),
'GET': lambda dynamo, x: dynamo.scan(**x),
'POST': lambda dynamo, x: dynamo.put_item(**x),
'PUT': lambda dynamo, x: dynamo.update_item(**x),
}
operation = event['requestContext']['http']['method']
if operation in operations:
payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
return respond(None, operations[operation](dynamo, payload))
else:
return respond(ValueError('Unsupported method "{}"'.format(operation)))
I changed the code from:
operation = event['httpMethod']
to
operation = event['requestContext']['http']['method']
How do I get this solution?
I simply returned the entire event, checked the JSON and put it to work with the correct format.
If event appears an empty object, make sure you enabled proxy integration for the method. Proxy integration for an HTTP method adds request information into event.
See Use Lambda Proxy integration on API Gateway page.
If you are using API gateway, http method will be automatically passed to the event parameter when the lambda is triggered.
export const handler: Handler<APIGatewayProxyEvent> = async (
event: APIGatewayEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
const httpMethod = event.httpMethod;
...
}

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

for instance if we want to use
GET /user?name=bob
or
GET /user/bob
How would you pass both of these examples as a parameter to the Lambda function?
I saw something about setting a "mapped from" in the documentation, but I can't find that setting in the API Gateway console.
method.request.path.parameter-name for a path parameter named parameter-name as defined in the Method Request page.
method.request.querystring.parameter-name for a query string parameter named parameter-name as defined in the Method Request page.
I don't see either of these options even though I defined a query string.
As of September 2017, you no longer have to configure mappings to access the request body.
All you need to do is check, "Use Lambda Proxy integration", under Integration Request, under the resource.
You'll then be able to access query parameters, path parameters and headers like so
event['pathParameters']['param1']
event["queryStringParameters"]['queryparam1']
event['requestContext']['identity']['userAgent']
event['requestContext']['identity']['sourceIP']
The steps to get this working are:
Within the API Gateway Console...
Go to Resources -> Integration Request
Click on the plus or edit icon next to the templates dropdown (odd I know since the template field is already open and the button here looks greyed out)
Explicitly type application/json in the content-type field even though it shows a default (if you don't do this it will not save and will not give you an error message)
put this in the input mapping { "name": "$input.params('name')" }
click on the check box next to the templates dropdown (I'm assuming this is what finally saves it)
I have used this mapping template to provide Body, Headers, Method, Path, and URL Query String Parameters to the Lambda event. I wrote a blog post explaining the template in more detail: http://kennbrodhagen.net/2015/12/06/how-to-create-a-request-object-for-your-lambda-event-from-api-gateway/
Here is the Mapping Template you can use:
{
"method": "$context.httpMethod",
"body" : $input.json('$'),
"headers": {
#foreach($param in $input.params().header.keySet())
"$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end
#end
},
"queryParams": {
#foreach($param in $input.params().querystring.keySet())
"$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
#end
},
"pathParams": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
}
}
These days a drop-down template is included in the API Gateway Console on AWS.
For your API, click on the resource name... then GET
Expand "Body Mapping Templates"
Type in
application/json
for Content-Type (must be explicitly typed out) and click the tick
A new window will open with the words "Generate template" and a dropdown (see image).
Select
Method Request passthrough
Then click save
To access any variables, just use the following syntax (this is Python)
e.g. URL:
https://yourURL.execute-api.us-west-2.amazonaws.com/prod/confirmReg?token=12345&uid=5
You can get variables as follows:
from __future__ import print_function
import boto3
import json
print('Loading function')
def lambda_handler(event, context):
print(event['params']['querystring']['token'])
print(event['params']['querystring']['uid'])
So there is no need to explicitly name or map each variable you desire.
In order to pass parameters to your lambda function you need to create a mapping between the API Gateway request and your lambda function. The mapping is done in the Integration Request -> Mapping templates section of the selected API Gateway resource.
Create a mapping of type application/json, then on the right you will edit (click the pencil) the template.
A mapping template is actually a Velocity template where you can use ifs, loops and of course print variables on it. The template has these variables injected where you can access querystring parameters, request headers, etc. individually. With the following code you can re-create the whole querystring:
{
"querystring" : "#foreach($key in $input.params().querystring.keySet())#if($foreach.index > 0)&#end$util.urlEncode($key)=$util.urlEncode($input.params().querystring.get($key))#end",
"body" : $input.json('$')
}
Note: click on the check symbol to save the template. You can test your changes with the "test" button in your resource. But in order to test querystring parameters in the AWS console you will need to define the parameter names in the Method Request section of your resource.
Note: check the Velocity User Guide for more information about the Velocity templating language.
Then in your lambda template you can do the following to get the querystring parsed:
var query = require('querystring').parse(event.querystring)
// access parameters with query['foo'] or query.foo
The accepted answer worked fine for me, but expanding on gimenete's answer, I wanted a generic template I could use to pass through all query/path/header params (just as strings for now), and I came up the following template. I'm posting it here in case someone finds it useful:
#set($keys = [])
#foreach($key in $input.params().querystring.keySet())
#set($success = $keys.add($key))
#end
#foreach($key in $input.params().headers.keySet())
#if(!$keys.contains($key))
#set($success = $keys.add($key))
#end
#end
#foreach($key in $input.params().path.keySet())
#if(!$keys.contains($key))
#set($success = $keys.add($key))
#end
#end
{
#foreach($key in $keys)
"$key": "$util.escapeJavaScript($input.params($key))"#if($foreach.hasNext),#end
#end
}
As part of trying to answer one of my own questions here, I came across this trick.
In the API Gateway mapping template, use the following to give you the complete query string as sent by the HTTP client:
{
"querystring": "$input.params().querystring"
}
The advantage is that you don't have to limit yourself to a set of predefined mapped keys in your query string. Now you can accept any key-value pairs in the query string, if this is how you want to handle.
Note: According to this, only $input.params(x) is listed as a variable made available for the VTL template. It is possible that the internals might change and querystring may no longer be available.
Now you should be able to use the new proxy integration type for Lambda to automatically get the full request in standard shape, rather than configure mappings.
see: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-set-up-lambda-proxy-integration-on-proxy-resource
GET /user?name=bob
{
"name": "$input.params().querystring.get('name')"
}
GET /user/bob
{
"name": "$input.params('name')"
}
The query string is straight forward to parse in javascript in the lambda
for GET /user?name=bob
var name = event.queryStringParameters.name;
This doesn't solve the GET user/bob question though.
A lot of the answers here are great. But I wanted something a little simpler.
I wanted something that will work with the "Hello World" sample for free. This means I wanted a simple produces a request body that matches the query string:
{
#foreach($param in $input.params().querystring.keySet())
"$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
#end
}
I think the top answer produces something more useful when building something real, but for getting a quick hello world running using the template from AWS this works great.
The following parameter-mapping example passes all parameters, including path, querystring and header, through to the integration endpoint via a JSON payload
#set($allParams = $input.params())
{
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
}
}
In effect, this mapping template outputs all the request parameters in the payload as outlined as follows:
{
"parameters" : {
"path" : {
"path_name" : "path_value",
...
}
"header" : {
"header_name" : "header_value",
...
}
'querystring" : {
"querystring_name" : "querystring_value",
...
}
}
}
Copied from the Amazon API Gateway Developer Guide
For getting query parameters you get them in queryStringParameters object like this
const name = event.queryStringParameters.name;
The second one is a clean URL. If your path is /user/{name}, to get the value you get it from pathParameters object like this
const name = event.pathParameters.name;
Python 3.8 with boto3 v1.16v - 2020 December
For configuring routes, you have to configure API Gateway to accept routes. otherwise other than the base route everything else will end up in a {missing auth token} or something other...
Once you configured API Gateway to accept routes, make sure that you enabled lambda proxy, so that things will work better,
to access routes,
new_route = event['path'] # /{some_url}
to access query parameter
query_param = event['queryStringParameters'][{query_key}]
As #Jonathan's answer, after mark Use Lambda Proxy integration in Integration Request, in your source code you should implement as below format to by pass 502 Bad Gateway error.
NodeJS 8.10:
exports.handler = async (event, context, callback) => {
// TODO: You could get path, parameter, headers, body value from this
const { path, queryStringParameters, headers, body } = event;
const response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify({
path,
query: queryStringParameters,
headers,
body: JSON.parse(body)
}),
"isBase64Encoded": false
};
return response;
};
Don't forget deploy your resource at API Gateway before re-run your API.
Response JSON just return which set in body is correct.
So, you could get path, parameter, headers, body value from event
const { path, queryStringParameters, headers, body } = event;
The Lambda function expects JSON input, therefore parsing the query string is needed. The solution is to change the query string to JSON using the Mapping Template.I used it for C# .NET Core, so the expected input should be a JSON with "queryStringParameters" parameter. Follow these 4 steps below to achieve that:
Open the mapping template of your API Gateway resource and add new application/json content-tyap:
Copy the template below, which parses the query string into JSON, and paste it into the mapping template:
{
"queryStringParameters": {#foreach($key in $input.params().querystring.keySet())#if($foreach.index > 0),#end"$key":"$input.params().querystring.get($key)"#end}
}
In the API Gateway, call your Lambda function and add the following query string (for the example): param1=111&param2=222&param3=333
The mapping template should create the JSON output below, which is the input for your Lambda function.
{
"queryStringParameters": {"param3":"333","param1":"111","param2":"222"}
}
You're done. From this point, your Lambda function's logic can use the query string parameters.
Good luck!
exports.handler = async (event) => {
let query = event.queryStringParameters;
console.log(`id: ${query.id}`);
const response = {
statusCode: 200,
body: "Hi",
};
return response;
};
You can used Lambda as "Lambda Proxy Integration" ,ref this [https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python] , options avalible to this lambda are
For Nodejs Lambda
'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables',
and 'event.requestContext'
For Python Lambda
event['headers']['parametername'] and so on
Refer Doc :
https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html#api-as-lambda-proxy-expose-get-method-with-path-parameters-to-call-lambda-function
You need to modify the Mapping Template
My goal was to pass a query string similar to:
protodb?sql=select * from protodb.prototab
to a Node.js 12 Lambda function via a URL from the API gateway. I tried a number of the ideas from the other answers but really wanted to do something in the most API gateway UI native way possible, so I came up with this that worked for me (as of the UI for API Gateway as of December 2020):
On the API Gateway console for a given API, under resources, select the get method. Then select its Integration Request and fill out the data for the lambda function at the top of the page.
Scroll to the bottom and open up the mapping templates section. Choose Request Body Passthrough when there are no templates defined (recommended).
Click on Add mapping templates and create one with the content-type of application/json and hit the check mark button.
For that mapping template, choose the Method Request passthrough on the drop down list for generate template which will fill the textbox under it with AWS' general way to pass everything.
Hit the save button.
Now when I tested it, I could not get the parameter to come through as event.sql under node JS in the Lambda function. It turns out that when the API gateway sends the URL sql query parameter to the Lambda function, it comes through for Node.js as:
var insql = event.params.querystring.sql;
So the trick that took some time for me was to use JSON.stringify to show the full event stack and then work my way down through the sections to be able to pull out the sql parameter from the query string.
So basically you can use the default passthrough functionality in the API gateway with the trick being how the parameters are passed when you are in the Lambda function.
The way that works for me is to
Go to Integration Request
click URL Query String Parameters
click Add query string
in name field put the query name, which is "name" here
in Mapped From field, put "method.request.querystring.name"
My 2 cents here: Lot of answers suggest to activate the option "Use Lambda Proxy Integration" and get the parameters from $.event.queryStringParameter or $.event.pathParameters. But if you happen to have Access-Control-Allow-Origin (a.k.a. CORS) activated, keep reading.
At the time of this post, Lambda Proxy integration and CORS don't work very well together. My approach was to deactivate the checkbox of Lambda Proxy integration and manually provide a Mapping templates for both request and response as follows:
Request template for application/json:
{
#set($params = $input.params().querystring)
"queryStringParameters" : {
#foreach($param in $params.keySet())
"$param" : "$util.escapeJavaScript($params.get($param))" #if($foreach.hasNext),#end
#end
},
#set($params = $input.params().path)
"pathParameters" : {
#foreach($param in $params.keySet())
"$param" : "$util.escapeJavaScript($params.get($param))" #if($foreach.hasNext),#end
#end
}
}
Mind that I named the properties as queryStringParameters and pathParameters on purpose, to mimic the names that Lambda Proxy integration would have generated. This way my lambdas won't break if one day I activate the Lambda Proxy integration.
Response template for application/json:
#set($payload = $util.parseJson($input.json('$')))
#set($context.responseOverride.status = $payload.statusCode)
$payload.body
How do you read these in your lambda (python)? (assuming parameters are optional)
def handler(event, context):
body = event["queryStringParameters"] or {}
result = myfunction(**body)
return {
"statusCode": code,
"headers": {
"content-type": "application/json",
},
"body": result
}
After reading several of these answers, I used a combination of several in Aug of 2018 to retrieve the query string params through lambda for python 3.6.
First, I went to API Gateway -> My API -> resources (on the left) -> Integration Request. Down at the bottom, select Mapping Templates then for content type enter application/json.
Next, select the Method Request Passthrough template that Amazon provides and select save and deploy your API.
Then in, lambda event['params'] is how you access all of your parameters. For query string: event['params']['querystring']