What is the getVar function?

The getVar function fetches the GET variables from an API query. This gives your API the ability to receive some input data that you could configure to change the output.

Let's make a simple math API for example. In this example, we are basically generating 2 numbers and then performing an operation on them. By default, the program will add the 2 numbers together and then assign the sum to a property called add. In this example, the user can completely change the functionality of this API by changing the operation that is performed by sending in an operation value through the URI.

If the operation passes our validation check, the program will end up using a different operator and result with completely different output.

// Fetch the value sent in through the operation GET variable
let operation = getVar('operation');

// Accepted operations that we will check against
let validOperations  = ["add", "sub", "mul", "div", "mod"];  
let operationSymbols = [ "+",   "-",   "*",   "/",   "%" ];

// Default value
let useOperation = "add";

// Only use sent in operation if it is in our list of valid operations.
let index = validOperations.indexOf(operation);

if (index !== -1) {  
    useOperation = operation;
} else {
    index = 0; // Add is 0.

api.num1 = random.numeric(1, 25);  
api.num2 = random.numeric(1, 25);

api[useOperation] = eval(`${api.num1}${operationSymbols[index]}${api.num2}`);  


  "num1": 15,
  "num2": 6,
  "sub": 9

For this example, the getVar result was fairly simple but it is easy to see how you can configure your API to have completely different behavior depending on the input that is sent in.