Add custom fields in REST API response?

Hello everyone,

I was wondering if we could create a custom response model for the default REST API ?

When I query /api/pages/my-page/children?select=content,slug, I would like to select my custom field as well.

I found the default model in kirby/config/api/models/Page.php where all the available fields are and I could simply add my custom field with some logic here but it is not a good practice as I modify kirby’s core.

I tried to create a page model to override the content() method to append my field but it has some unwanted side effects.

Maybe some of you have already found a workaround for this ?
Have a nice day !

You custom field should be part of content like any other field.

Ok I understand and how should I do if I need some logic to process the field before exposing it in the API response ?

I would have suggested to overwrite the content method in a page model, but looks like you already tried that? But don’t know what you tried, given that you thought you had to add the field somehow.

An alternative would be a custom API endpoint.

I tried this page model below :

<?php

  use Kirby\Cms\Content;

  class TrackPage extends Page {

    public function content (string $languageCode = null) {

      // some logic here
      $value = 'value after processing data';

      $field = [
        'mycustomfield' => $value
      ];

      return $this->content = new Content($this->readContent() + $field, $this, false);
    }

  }

I do have mycustomfield now in the API response. But when I save a page in the panel, it seems like Kirby is using the content() method to write in the .txt file where I now have a new entry mycustomfield.

In my case, the custom processed field is a big array, I don’t really want it to be saved in the .txt file … Maybe I am doing something wrong ?

Ok, you didn’t mention that your field is not supposed to save anything. While it is true that there are fields that do not store anything (gap field, headline), it’s not the default behavior of fields.

Where does the data from that custom field come from? API? Database? And why a field?

In that case, the custom API endpoint probably makes more sense.

I need to generate a waveform from an uploaded mp3 audio. I have a page.update:after hook to create a JSON that contains the data.

I use Kirby as a headless CMS so I want to return the content of the JSON file in the API response without having to make 2 calls (one to get the JSON url and one to fetch the JSON content).

I will go for the custom API endpoint then, thank you very much for your answers.