Reputation: 23216
I have been stuck here for too long. How do I enable API Key for the particular REST method using the aws-sdk
? I could enable it using the console, but not finding a method to achieve this using the nodejs sdk. So basically want to setup the secret key for specified API Endpoint + Resource + Method.
In the following snapshot, I enabled the api-key required to true
from the console.
Docs referred: AWS Nodejs Doc
Here is what I have been able to do so far:
// CREATE API KEY
async function create() {
try {
const apiKey = await apigateway.createApiKeyAsync({
enabled: true,
generateDistinctId: true,
name: NAME_OF_KEY
});
/**
* @see https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/APIGateway.html#createUsagePlan-property
*/
// CREATE USAGE PLAN AND LINK API
const usagePlan = await apigateway.createUsagePlanAsync({
name: NAME_OF_USAGE_PLAN,
apiStages: [
{
apiId: API_ID,
stage: STAGE
},
/* more items */
],
quota: QUOTA_INFO,
throttle: THROTTLE_INFO
});
/**
* Creates a usage plan key for adding an existing API key to a usage plan.
*/
// LINK API KEY AND USAGE PLAN
await apigateway.createUsagePlanKeyAsync({
keyId: apiKey.id,
keyType: 'API_KEY',
usagePlanId: usagePlan.id
});
return Promise.resolve(apiKey);
} catch (err) {
return Promise.reject(err);
}
}
Upvotes: 1
Views: 519
Reputation: 33726
You need to call the function updateMethod
to update your method request:
Reference: Class: AWS.APIGateway
var params = {
httpMethod: 'STRING_VALUE', /* required */
resourceId: 'STRING_VALUE', /* required */
restApiId: 'STRING_VALUE', /* required */
patchOperations: [
{
from: 'STRING_VALUE',
op: add | remove | replace | move | copy | test,
path: 'STRING_VALUE',
value: 'STRING_VALUE'
},
/* more items */
]
};
apigateway.updateMethod(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
So you can do the following:
var apigateway = new AWS.APIGateway({apiVersion: '2015-07-09'});
var params = {
httpMethod: 'POST',
resourceId: 'resource id',
restApiId: API_ID,
patchOperations: [
{
op: 'replace',
path: '/apiKeyRequired',
value: 'true' || 'false'
},
]
};
apigateway.updateMethod(params, function(err, data) {
if (err) cb(err, err.stack); // an error occurred
else cb(null, data); // successful response
});
Hope it helps!
Upvotes: 1