# API

- Read more: <https://getkirby.com/docs/guide/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.

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

Kirby::plugin('my/api', [
  'api' => [
    'routes' => [
      [
        'pattern' => 'my-endpoint',
        'method' => 'GET', // optional, defaults to 'GET'
        '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 <a href="https://getkirby.com/docs/guide/api#custom-api-location">change the API slug</a>.

### Access to `$kirby`

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

```php "/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 <a href="https://getkirby.com/docs/guide/api/data#data-provider-functions">data provider functions</a> 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.

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