Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add API Key to Usage Plan in AWS API Getaway

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: enter image description here

However I could not find a similar function in AWS SDK documentation

like image 334
bpavlov Avatar asked Dec 07 '16 10:12

bpavlov


People also ask

Can I use API key without usage plan?

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.


2 Answers

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"

like image 83
bpavlov Avatar answered Sep 19 '22 16:09

bpavlov


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;
}
like image 44
PadawanQ Avatar answered Sep 18 '22 16:09

PadawanQ