Aws api gateway client module - node-modules

How will i pass a responseType value with aws-gateway-client module invokeApi function.Tried to pass it as additional parameters,headers,pathparameters and all.
invokeUrl:Xxxxxxxxxxxxxxx,
region:Xxxxxxxx,
accessKey:xXxxxxxxxxxx,
secretKey:xxxxxxxxxxxxxx
});
var res= await apigClient.invokeApi(pathParamas,pathTemplate,method,additionalParams,data).then(function to handle response data).catch(error handling function)```

Related

Pass variables between different server-less functions

I am building an application using the Twitter API and Netlify (aws lambda functions)
This API requires these steps:
When the user goes to my /auth function, a link to the Twitter authentication is created
Once the user clicks that link, he is redirected to Twitter where a pop-up asks to allow my app to connect.
Once the user approves, he is redirected to my /auth function again but this time the authCode is set to a number rather than being undefined. This authCode is used to instantiate the twitter client class and authorize it.
A new instance of the Twitter client is created and authorized. This instance allows to query the tweets
1, 2 and 3 works. However, the authorized instance only lives inside the /auth function. How can I pass it to different functions without losing its instantiation?
How can I pass this instance to different server-less functions?
client = new Client(OAuthClient) this is what I want to pass around.
I tried with a Middleware with little success. It seems the twitter client class gets re-instantiated (so without authorization) for every server-less function
https://playful-salmiakki-67d50e.netlify.app/.netlify/functions/auth
import Client from 'twitter-api-sdk';
let client: Client;
const auth = async (event, context, callback) => {
const authCode = event.queryStringParameters ? event.queryStringParameters.code : undefined;
const authUrl = OAuthClient.generateAuthURL({
state: 'STATE',
code_challenge: 'challenge',
});
console.log('HERE LINK:');
console.log(authUrl);
if (authCode) {
await OAuthClient.requestAccessToken(authCode as string);
client = new Client(OAuthClient); <-- THIS IS WHAT I WANT TO PASS TO DIFFERENT FUNCTIONS
}
return {
statusCode: 200,
body: JSON.stringify({ message: 'Auth, go to the url displayed terminal'}),
myClient: client
};
};
exports.handler = middy().use(myMiddleware()).handler(auth);

Error BadRequestException: You must use the customer-specific endpoint

I am trying to create job of mediaconverter aws service through lambda but I m getting error
"Error BadRequestException: You must use the customer-specific
endpoint"
AWS.config.update({region: 'us-east-1'});
var mediaconvert = new AWS.MediaConvert("https://xyzyzyzzz.mediaconvert.us-east-1.amazonaws.com");
console.log("End Point Set");
await mediaconvert.createJob(params, function(err, data) {
console.log('started execution');
if (err){ console.log(err, err.stack);
console.log("non promise error");
callback(null, {
statusCode: 200,
body: JSON.stringify(data)
});
} // an error occurred
else { console.log("non promise no error");
callback(null, {
statusCode: 200,
body: JSON.stringify(data)
});
}
// successful response
});
the easiest way to find you mediaconvert endpoint is to go to mediaconvert service -> from left panel select account and there's your endpoint.
I found mine https://xxxxx.mediaconvert.ap-south-1.amazonaws.com
Hope this helps.
You did not specify the params in your createJob call.
The documentation tells you what you need in order to create a job.
That is the error you get when the endpoint is not specified or if it's an invalid value. The constructor for MediaConvert accepts an object, not just a string, as outlined in the docs. You need to pass the endpoint URI in an object like so:
var mediaconvert = new AWS.MediaConvert({
endpoint: "https://xyzyzyzzz.mediaconvert.us-east-1.amazonaws.com"
});
For context, the endpoint can be found in the console in the MediaConvert service under the Account section or it can be fetched through the API as outlined here. In general, this value should be cached as it has a much lower request rate limit than the other MediaConvert endpoints. There is one endpoint per account per region.

GET request with query parameters returns 403 error (signature does not match) - AWS Amplify

Problem
I was trying to use 'aws-amplify' GET API request with query parameters on the client side, but it turned out to be Request failed with status code 403, and the response showed:
"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Note: React.js as front-end, Javascript as back-end.
My code
Front-end
function getData() {
const apiName = 'MyApiName';
const path = '/path';
const content = {
body:{
data:'myData',
},
};
return API.get(apiName, path, content);
}
Back-end
try {
const result = await dynamoDbLib.call("query", params);
} catch (e) {
return failure({ status: false });
}
What I did to debug
The GET lambda function works fine in Amazon Console (Tested)
If I change the backend lambda function so that the frontend request can be made without parameters, i.e. return API.get(apiName, path), then no error shows up.
My question
How can I make this GET request with query parameters works?
I changed GET to POST (return API.post()), everything works fine now.
If anyone can provide a more detailed explanation, it would be very helpful.

Redirect link to distribution slack app

I'm trying to redirect URL to distribute (OAuth 2.0)my slack app with API gateway and lambda function (AWS) but I can't realize how to get the code.
the event that returns is null.
My lambda code :
// Lambda handler
exports.handler = (event, context, callback) => {
var messageTest = {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code: event.code
};
var queryTest = qs.stringify(messageTest);
https.get(`https://slack.com/api/oauth.access?${queryTest}`, (res, err) => {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
var data = [];
res.on('data', function(chunk) {
data.push(chunk);
});
res.on('end', function() {
var result = JSON.parse(data.join(''))
console.log(result);
});
});
callback(null);
};
My redirect URL is the lambda URL.
The event that i get is null.
How can i get the "code" from the oAuth 2.0?
Assuming you are using Lambda Proxy integration (and therefore you don't use a Body Mapping Template), the JSON payload that you send to your API Gateway will be received by your Lambda as a stringified JSON in event.body.
So, you'll need to parse that first and you can get your code.
const body = JSON.parse(event.body)
const code = body.code
Reference: Input Format of a Lambda Function for Proxy Integration

Making a POST request using Superagent, AWS Lambda, API Gateway

I am using AWS Lambda and API Gateway to create a custom endpoint for load tests. I have uploaded my handler function which is in a file, along with the node modules needed for the function in a zip, and set up the API Gateway API correctly according the instructions (in line with the way that I had made it work before), but I keep getting the error: {"error": "Missing Authentication Token"}. Everything I have seen online thus far points to the idea that the url that I am passing in with the POST request is invalid, but I have made a similar endpoint work with a GET request. As far as I know I have set up the POST request (using Superagent) correctly, and am passing in a valid access-token, as well as hardcoded params as part of the URL (valid params).
// Dependencies
var request = require('superagent');
var sync = require('synchronize');
exports.handler = function(event, context) {
sync.fiber(function() {
// Grabs params passed into the URL as a JSON object
var querystring = (event.querystring);
// Replaces params with an updated version which includes a single quotation
var queryStringUpdate = querystring.replace(/=/g, ":").replace(/}/g, "'}").replace(/:/g, ":'").replace(/,/g, "',");
// Updates the param information and sets it as a new string
eval('var queryString2 =' + queryStringUpdate);
// Define specific query params to be used in the REST calls
var userId = (queryString2.userId === undefined ? '229969' : queryString2.userId);
var roomdId = (queryString2.roomId === undefined ? '4' : queryString2.roomId);
var inviterId = (queryString2.inviterId === undefined ? '212733' : queryString2.inviterId);
var createInvitePost = function() {
request
.post('https://some_url/v2/invites/212733/create')
.set({'access-token': 'some_access_token'})
.set('Content-Type', 'application/json')
.query({user_id: "229969"})
.query({room_jid: "4"})
.end(function(err, res){
if (err) {
context.fail("Uh oh, something went wrong");
} else {
context.done(null, "Hurray, it worked!!");
}
});
};
try {
createInvitePost();
} catch(errOne) {
alert("No bueno!!");
}
});
};
Any thoughts on this?? Thanks
I usually get this error when I've missed some part of the URL needed for my API. In the past it's either been the name of the stage, misspelled resource name, or a missing Path parameter.
I'm from the Api Gateway team.
As others have said, the most common cause of the 403 response you're getting is an incorrect path/method. I'm not familiar with Superagent, but if you've run the same request in Postman and cURL then I would be surprised if you had the wrong path/method.
Maybe also check on a wire log if possible, to make sure that your querystring logic isn't appending a forward slash prior to the '?'.
Some things to check:
Have you deployed any recent changes to your API?
Is the stage 'v2' (I'm assuming that's the stage) pointing at a deployed version of the API that has the POST to invites/212733/create?
The 'access-token' should have no effect on the Api Gateway layer. If you're trying to use a native Api Gateway Api Key, the header is 'x-api-key'.
Jack

Resources