REST APIs

Offering a RESTful API is not different from creating a route and controllers for the web interface. It is recommended though to inherit from ApiController and add @CORS annotations to the methods so that web applications will also be able to access the API.

  1. <?php
  2. namespace OCA\MyApp\Controller;
  3. use \OCP\AppFramework\ApiController;
  4. use \OCP\IRequest;
  5. class AuthorApiController extends ApiController {
  6. public function __construct($appName, IRequest $request) {
  7. parent::__construct($appName, $request);
  8. }
  9. /**
  10. * @CORS
  11. */
  12. public function index() {
  13. }
  14. }

CORS also needs a separate URL for the preflighted OPTIONS request that can easily be added by adding the following route:

  1. <?php
  2. // appinfo/routes.php
  3. array(
  4. 'name' => 'author_api#preflighted_cors',
  5. 'url' => '/api/1.0/{path}',
  6. 'verb' => 'OPTIONS',
  7. 'requirements' => array('path' => '.+')
  8. )

Keep in mind that multiple apps will likely depend on the API interface once it is published and they will move at different speeds to react to changes implemented in the API. Therefore it is recommended to version the API in the URL to not break existing apps when backwards incompatible changes are introduced:

  1. /index.php/apps/myapp/api/1.0/resource

Modifying the CORS headers

By default the following values will be used for the preflighted OPTIONS request:

  • Access-Control-Allow-Methods: ‘PUT, POST, GET, DELETE, PATCH’
  • Access-Control-Allow-Headers: ‘Authorization, Content-Type, Accept’
  • Access-Control-Max-Age: 1728000

To add an additional method or header or allow less headers, simply pass additional values to the parent constructor:

  1. <?php
  2. namespace OCA\MyApp\Controller;
  3. use \OCP\AppFramework\ApiController;
  4. use \OCP\IRequest;
  5. class AuthorApiController extends ApiController {
  6. public function __construct($appName, IRequest $request) {
  7. parent::__construct(
  8. $appName,
  9. $request,
  10. 'PUT, POST, GET, DELETE, PATCH',
  11. 'Authorization, Content-Type, Accept',
  12. 1728000);
  13. }
  14. }