Extend API data provider

I couldn’t find anything related in the docs but I wonder if we can extend or adapt an existing data provider. What I’m trying to achieve is to add or adapt a field to the response.

For example change "url":"http:\/\/localhost:3010\/notes\/in-the-jungle-of-sumatra" to "slug":"\/notes\/in-the-jungle-of-sumatra".

I know I could iterate through the collection or create a new one but maybe there is a more convinient way to tackle this :slight_smile:

Given is this code which returns JSON

Kirby::plugin('gearsdigital/kirby-better-link', [
    'api'          => [
        'routes' => [
            [
                'pattern' => 'better-link/pages',
                'method'  => 'get',
                'action'  => function () {
                    $page = get('page');
                    $query = get('search', '*');

                    return site()->search($query, 'title')->paginate([
                        'page'  => $page,
                        'limit' => 1,
                    ]);
                },
            ],
        ],
    ],
]);

Response

{
   "code":200,
   "data":[
      {
         "id":"notes\/in-the-jungle-of-sumatra",
         "num":20180731,
         "title":"In the jungle of Sumatra",
         "url":"http:\/\/localhost:3010\/notes\/in-the-jungle-of-sumatra"
      },
   ],
   "pagination":{
      "page":1,
      "total":21,
      "offset":0,
      "limit":1
   },
   "status":"ok",
   "type":"collection"
}

@texnixe Do you have any insights here?

Nope, no idea.

@distantnative?

1 Like

I wonder if the API response can be adapted. The API stuff does a lot of black magic and can’t figure out why each returned data object has always the same properties:

{
  id,
  num,
  title,
  url
}

Okay, it seems the above mentioned default object is calledview and is defined in models/Page.php.

There some views defined. compact is above mentioned default object.

I can append a query parameter to the API URL and change the view to one of the defined ones: /api/my-endpoint?page=1&view=default

The response has now changed from

{
  id,
  num,
  title,
  url
}

to this:

{
  content,
  id,
  status,
  num,
  options,
  parent,
  slug,
  template,
  title,
  url
}

Is it possible to define custom API Response models?

Docs coming soon :see_no_evil:

Unfortunately, these promises have been there ever since the release of Kirby 3, and if I had the faintest idea what these are I’d write them, but …

Hehe… I currently read the ApiTest files and try to understand what heck is this all about.

I have a feeling that @distantnative who could shed some light on this is on some sort of vacation in a distant location without internet access (hardly believable).

1 Like

Resting is important! :smiley: Let’s wait till he comes back.

@distantnative @distantnative @distantnative

1 Like

Got it!* Will provide my solution later :smiley:

Spoiler: *It’s not the data provider.

1 Like