I have deployed AWS stack with a Lambda function and an API gateway. After deployment I tested Lambda function independently and it works fine but when I invoke it using AWS API Gateway, it fails with `
Internal Error: 502
I looked at cloudwatch logs and it says
Endpoint response body before transformations: null
I am returning my response from Lambda (Python 3.6) in following way -
body = {
"message": "Success!!"
}
response = {
"statusCode": 200,
"headers": {
"content-type": "application/json"
},
"body": json.dumps(body),
"isBase64Encoded": False,
}
return response
Ok, I found the problem. Actually the code is correct. I made few changes and took the above code outside handler. So my handler was calling this new function and it was returning response to handler but I missed to return the received response again from handler to API gateway.
Related
I have an ALB that has lambda as target group. Essentially, the lambda that does logic checks and returns a response:
{
'statusCode': 301,
'headers': {
'Location': url,
},
'body': null,
'isBase64Encoded': false
}
The response above will return a 502 bad gateway, which doesn't really help with debugging the issue. Cloudwatch says it returns the response above. The logic before the response works just fine. I would test with a status code 200, content-type application/json and a debugging message, which would return properly to the user. I know ALB has a listener for redirects, but the lambda has to go through logic to properly redirect someone first which requires things from secret manager. So the question stands, are there any other ways to redirect with alb using lambda? I tried searching through documentaries to see if there are any other limitations with lambdas as a target group. Other than the 1 mb payload/request and formatting response payload, I haven't seen anything of notice.
Sadly no. It's not lambdas role in alb to perform any redirections. If you use CloudFront, you can use lambda functions in your distribution to do redirections instead.
What you're aiming to do is possible.
What error message do you get, when you call the lambda directly (e.g. from AWS management console)?
I could successfully test your use case with a lambda with following implementation (node run time):
export const handler = async (event) => ({
statusCode: 302,
headers: {
Location: 'https://your-url/'
}
});
I am currently playing around a bit with AWS AppSync and I am trying to use the Lambda authoriser feature to do some custom auth for the GraphQL API.
I have the Lambda function set up with the correct resource-based policy to allow AppSync to invoke the function and I have AppSync's Default authorization mode set to invoke my Lambda.
This is my lambda code:
exports.handler = (event) => {
console.log(JSON.stringify(event));
const response = {
isAuthorized: true,
};
console.log(JSON.stringify(response));
return response;
};
Now I am facing the issue that the Lambda authoriser is always giving me the following error when I attempt to run a GraphQL quarry:
Error: Request failed with status code 401
After debugging this problem for two hours I can say the following things:
The GraphQL endpoint is working fine, because if I set the Default authorization mode to API key or Amazon cognito user pool without changing anything else my Query executes successfully.
The lambda function is definitely being invoked whenever I make a request to the API and the lambda also receives the correct event from AppSync.
The Lambda returns {"isAuthorized":true} which means no Authorization Token would result in a 401.
So as far as I can tell everything is as it should but I am still getting the 401 no matter what I do and im getting pretty frustrated.
Whenever you receive an Error: Request failed with status code 401 in your AWS AppSync Console and you were using Lambda Authorizer as your custom Authorizer for your API. Irrespective of what are the frameworks you used to create the Infrastructure i.e., CDK or SAM or Serverless Framework. Check whether you have added these correctly for your Lanbda Authorizer
Check you have added proper policystatement to your Lambda Authorizer
Check you have added permission for your Lambda Authorizer to your API
Eg:
If you are using AWS CDK to create all your AppSync and Lambda Authorizer, Add these two things to solve the above error
lambdaAuth.addToRolePolicy("your policy statement"),
lambdaAuth.addPermission("appsync",{
principal: new ServicePrincipal("appsync.amazonaws.com"),
action: "lambda:InvokeFunction"
})
After some very frustrating debugging I finally figured out that the problem was the Lambda handler function. As it turns out a Node.js lambda handlers should be async.
So changing the lambda to the following code fixes the issue:
exports.handler = async (event) => {
console.log(JSON.stringify(event));
const response = {
isAuthorized: true,
};
console.log(JSON.stringify(response));
return response;
};
I didn't know this, since until no I only used Python for Lambdas, and the problem was hard to spot since the console.log's where still running correctly so I though the function was returning the correct data where as in fact it was returning null.
I am using an AWS Websocket API Gateway that has the following routes:
I've been able to connect to my websocket and send requests and receive responses from /SendMessage with the following json: {"action": "SendMessage", "message": "Hello, World"} however, when I tried adding a new route /Register. Sending the json {"action": "Register", "message": "Hello, World"} AWS API Gateway routes the request to $default.
The following request appears on CloudWatch:
The request should be routed to /Register and not /default. Do I need to do some kind of redeployment of the API Gateway when I add a new route?
First, make sure you have re-deployed your API Gateway.
Second, make sure you have re-deployed your Lambda functions
Last, you have to Stringify your request like this:
socket.send(JSON.stringify({
"action": "SendMessage",
"message": "Hello, World"
}))
I created a lambda function with a API gateway and Cloudfront distribution in the front
in the cloudfront behaviors I disabled caching
this is the lambda function:
exports.handler = async (event) => {
const response = {
statusCode: 200,
body: JSON.stringify('rawQueryString is: ' + event.rawQueryString),
};
return response;
};
calling the api gateway I see the querystring in the lambda response
https://xxx.execute-api.us-east-1.amazonaws.com/api?name=john
rawQueryString is: '?name=john'
calling the cloudfront distribution i can't see the querystring in the lambda response
https://xxx.cloudfront.net/api?name=john
rawQueryString is: ''
I tried with "Origin Request Policy"
but now when i call https://xxx.cloudfront.net/api?name=john
I get
{
"message": "Forbidden"
}
You should setup origin request policies for your cache behavior. You can try with AWS managed Managed-AllViewer policy or create new one just to forward the query strings:
This has been answered properly here
You cannot send Host - so make an Origin Policy passing as much as you want - but do not pass Host ! That's what produces the Forbidden.
https://kuchbhilearning.blogspot.com/2022/10/pass-query-params-from-cloudfront-to.html
We need to enable the cloudfront origin, this can also be done through CDK through addBehaviour or default ones.
REQUEST: POST body to ApiGateway to Lambda with Content-type:text/plain
RESPONSE: "message": "Internal server error"
Body example:
{"a":"first", "b":"second"}
Which configuration did i need to change to accept this Content-Type?
For json/application, it works just fine.
When creating a resource, use lambda proxy integration.
For more information read here.