Writing the Code

api init

Running api init will walk you through the steps to create your first service. It will ask you a few questions about your api. Make sure to do this inside of the folder you want everything to be created in!

Defining an endpoint

After running api init, you will notice that there is an endpoints directory containing a file like the one below. Don't worry about the comments for now, we will address that in the next section.

/*
 * Add a one line description of your service here
 *
 * Add a longer description of your service here. This can be as
 * long as you need it to be and also be on multiple lines.
 *
 * @param {string} name Name of the person
 * @throws {ValidationError} Must provide all required fields
 * @returns {Object} The created user object
 */
module.exports = (data, api) => {
  api.success('Hey there ' + data.name + '! It worked!');
};

Each file in the endpoints directory should have one export, which is what will get called by the consumer. The name of the endpoint is given by the file name, so in the above example, it will be called hello.

api.success

Once your service is complete and you want to return a successful result, you need to call api.success. You can pass any value into api.success and it will be passed back to the caller of your service.

api.success('Hey there ' + data.name + '! It worked!');

api.error

If we wanted to respond with an error if someone doesn't pass in a name, we can do that by adding the following code:

if(!data.name) api.error('ValidationError');

When the user calls this service without a name, they will receive an error response with the name "Validation Error" and the message provided in the documentation.

In the example above the following error is returned:

{ 
  error: 'Must provide all required fields',
  code: 'ValidationError',
  data: { 
    handled: true, 
    arguments: {}, 
    version: '1.0.0'
  }
}

Putting it all together

This is an example of a simple action that just multiples an array of numbers together.

/*
  Multiply an array of numbers together
  This will multiply an array of numbers together! It's really cool.
  @param {number[]} numbers - numbers to multiply
  @throws {paramRequired} Array of numbers is required
  @returns {number} Multiplied numbers
*/
module.exports = (data, api) => {
  if (!data.numbers) {
    api.error('paramRequired');
  }

  let output = 1;
  for (const i of data.numbers) {
    output *= i;
  }

  api.success(output);
};