I have an API that is connected to a lambda function that has queryStringParameters. On the function end I have
VARIABLE = event['queryStringParameters']['variable']
When I deploy my API and try to use it "api_url"?variable=something,
I get {"message": "Internal server error"}.
In Cloudwatch I get:
[ERROR] KeyError: 'queryStringParameters'
Traceback (most recent call last):
File "/var/task/index.py", line 217, in handler
VARIABLE = event['queryStringParameters']['variable']
To help troubleshoot I print the event. In Cloudwatch it does, and it appears as "{}", so pretty much as empty.
When I test the function in the console I use the event:
{ "queryStringParameters": {"variable": "T"}}
and the function works just fine.
I've made APIs that are connected to lambda functions before almost identical to this and have had no problem. I'm stumped. Any advice is appreciated.
Based on this AWS guide, you can access the query string parameters using get methods of the event object.
query_string = event.get('queryStringParameters')
if query_string is not None:
name = query_string.get('variable')
In your lambda's case, its quite strange that no queryStringParameters key could be found on the event object. It would be interesting to see if there's an actual parameter sent to the REST API or if the positioning of parameters in the handler's parameters are correct and that the parameter is provided on all requests.
def event_handler(event, context): # Make sure event goes first
query_string = event.get('queryStringParameters')
if query_string is None:
// Return 400 / 422 here to indicate a bad request
I have 3 webhooks that calls my API Gateway which calls my Lambda Function.
url/webhook/....
I want each webhook to call its own python method
startDelivery --> def start_delivery(event, context):
UpdateStatus--> def update_status(event, context):
EndDelivery--> def end_delivery(event, context):
I understand most likely one method will be executed via "url/webhook" which calls the appropriate python method.
def Process_task to call one of the three
What is the ideal way to set up this structure?
Creating different urls for Webhooks and API Gateway captures it and somehow calls the handler?
url/webhook/start
url/webhook/status
url/webhook/end
Sending a different query string for each webhook? and in the lamba parse the query string and call the right python method?
Keep in mind that a Lambda function has one handler (=> 1 invocation = 1 method called).
You can achieve the 1 route <-> 1 method by doing one of the following:
You have a single Lambda function triggered by your 3 APIGW routes.
You can then add a simple router to your function which parse the event['path'] and call the appropriate method.
def lambda_handler(event, context):
path = event['path']
if path == '/webhook/start':
return start_delivery(event, context)
elif path == '/webhook/status':
return update_status(event, context)
elif path == '/webhook/end':
return end_status(event, context)
else:
return { "statusCode": 404, "body": "NotFound" }
Create 1 Lambda function by route:
webhook/start triggers the StartDelivery Lambda function with start_delivery as handler
webhook/status triggers the UpdateDelivery Lambda function with update_delivery as handler
webhook/end triggers the EndDelivery Lambda function with end_delivery as handler
You can use Infrastructure as Code (Cloudformation) to easily manage these functions (SAM: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-getting-started-hello-world.html)
acorbel's answer was helpful for me. The latest version is Format 2.0. Many fields have changed. For example event['path'] doesn't exist with Format 2.0.
Please check the below link for correct key names of event structure.
Working with AWS Lambda proxy integrations for HTTP APIs
Im trying to create a simple API gateway in which, with a POST method to a certain endpoint, a lambda function is executed.
Setting that up was easy enough, but I'm having some trouble with the request/response handling. Im sending the following request to the API Gateway (Im using python 3.7).
payload = {
"data": "something",
"data2": "sometsadas"
}
response = requests.post('https://endpoint.com/test', params = payload)
That endpoint activates a lambda function when accesed. That function just returns the same event it received.
import json
def lambda_handler(event, context):
# TODO implement
return event
How can I make it so the return value of my lambda function is actually the response from the request? (Or at least a way in which the return value can be found somewhere inside the response)
Seems it was a problem with how the information is sent, json format is required. Solved it by doing the following in the code.
payload{'data': 'someData'}
config_response = requests.post(endpointURL, data = json.dumps(config_payload))
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
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;
...
}