Skip to content

Kirby 4.4.1

API

Kirby's REST API can be customized in various ways via the api extension.

Custom endpoints

If you want to provide your own API endpoints for your plugin and make use of our authentication and other API features, you can define them as the routes option of the api extension. Endpoint routes are defined as an array of key/value pairs. You have to define at least a pattern and an action.

/site/plugins/api/index.php
<?php

Kirby::plugin('my/api', [
  'api' => [
    'routes' => [
      [
        'pattern' => 'my-endpoint',
        'action'  => function () {
          return [
            'hello' => 'world'
          ];
        }
      ]
    ]
  ]
]);

Your new endpoint is now available at https://yourdomain.com/api/my-endpoint and will return a json encoded version of the returned array.

The endpoint is automatically protected with the same authentication layer as our own endpoints. It will also move when you change the API slug.

Access to $kirby

API endpoints can also be registered as callbacks. Within the callback they have full access to the current Kirby instance.

/site/plugins/your-plugin/index.php
<?php
Kirby::plugin('my/api', [
  'api' => [
    'routes' => function ($kirby) {
      return [
        [
          'pattern' => 'my-endpoint',
          'action'  => function () use ($kirby) {
            return [
              'users' => $kirby->users()->count()
            ];
          }
        ]
      ];
    }
  ]
]);

Custom data provider functions

You can register your own API data provider functions as the data option of the api extension. They are pretty handy if you need to fetch the same kind of data in multiple endpoints.

Kirby::plugin('my/api', [
  'api' => [
    'data' => [
      'message' => function () {
        return 'world';
      },
    ],
    'routes' => [
      [
        'pattern' => 'my-endpoint',
        'action'  => function () {
          return [
            'hello' => $this->message()
          ];
        }
      ]
    ]
  ]
]);