• Getting Started

Building an API

Modules can add public API methods that can be consumed by their own UI (see Creating an interface and Using AngularJS) and by external applications that want to access the module’s data.

Adding to module.json

You must create an ‘api’ controller and add API methods to your module.json file. Every API method specified has a path (the object’s key) and a function to be called (the object value). This function must exist inside the file that is indicated as the API controller (in this example: api/index.php).

module.json

{
   "controllers": {
      "api": "api/index.php"
   },
   "apiMethods": {
      "courses/:id": "view_course",
      ...
   }
}

Calling API methods

Specified API methods are added to the community namespace. To call the method defined in the example above, we call:

https://api.includable.com/2.0/communities/demo.includable.com/courses/204

Our view_course function in api/index.php may look like:

api/index.php

<?php

function view_course($container, $context){
   if(empty($context->id)){
      $container->api->error('Missing ID parameter!');
   }

   return array(
      'sample' => array('API', 'method', 'output'),
      'foo' => 'bar'
   );
}

What you can see from this example is that every API function must accept two parameters:

  • $container – The Container object, that is available as $this for most of the other controllers
  • $context – An object that contains parameters:
    • Parameters extracted from the URL (indicated by a colon in the URL format, i.e. ‘/courses/:id’ is available as $context->id)
    • POST form fields (instead of using $_POST[‘field’], use $context->field, because it is already filtered for certain types of script attacks)
    • When both a URL-parameter and a POST field with the same name are set, $context->field returns the POST field value.

There are two ways to return data to the client:

  • $container->api->error($message); will yield a error response with the specified error message.
  • Otherwise the return value of the function is used as the API result.

More details about checking if a user is a manager, errors, checking input and other available API features can be found in the API object reference.

Community API endpoint

If you want to consume your own API through an interface in the community itself (a web controller), there is a custom API endpoint that already has the user credentials and community context.

Consider being signed in as a user to a community that is located at https://demo.includable.com/. The API endpoint for that community is:

https://demo.includable.com/_api/2.0/communities/:c/

The API automatically replaces every instance of :c or :u in the URL by respectively the Community ID or User ID.

If our API is available at /courses/:id, the full URL for course 204 would be:

https://demo.includable.com/_api/2.0/communities/:c/courses/204