I have a problem with creating API Key associated with an Usage Plan in AWS API Getaway (using AWS SDK for node.js).
In AWS Console you can attach API Key to Usage Plan via this button:
However I could not find a similar function in AWS SDK documentation
In order for API keys to work, you need to: Create a usage plan (it does not have to have any throttling or quota) Add your API and stage to the usage plan. Add your API key to the usage plan.
This code do the magic:
var params = {
keyId: 'STRING_VALUE', /* required */
keyType: 'STRING_VALUE', /* required */
usagePlanId: 'STRING_VALUE' /* required */
};
apigateway.createUsagePlanKey(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
What I was missing was that keyType must be "API_KEY"
This is a full example of creating an API Key and assigning it to a usage plan.
async function createApiKey(apikey_name, usage_plan="free") {
const usage_plans = {
free: "kotc0f", // usage plan IDs
basic: "ju5fea"
};
if (!usage_plan || !(usage_plan in usage_plans)) {
console.log(usage_plan + " usage plan does not exist");
return false;
}
var params = {
name: apikey_name,
description: "Created via API on " + (new Date).toISOString(),
enabled: true,
generateDistinctId: true
};
let api_key = await new Promise((resolve) => {
apigateway.createApiKey(params, function (err, data) {
if (err) {
console.log("ERROR", err, err.stack); // an error occurred
resolve(false);
}
else {
resolve(data);
}
});
});
if (!api_key) return false;
params = {
keyId: api_key.id,
keyType: "API_KEY",
usagePlanId: usage_plans[usage_plan]
};
await new Promise((resolve) => {
apigateway.createUsagePlanKey(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
resolve(false);
}
else {
resolve(data);
}
});
});
return api_key;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With