Kirby REST API via HTTP in JSON format

Hi, @brandondurham there’s 3 main files, I stay with page called “Events”, but it can be a Blog, Portfolio etc.:

// plugins/api.php
<?php

$prefix = "api/v1";

kirby()->routes([
  [
    'method' => 'GET',
    'pattern' => "{$prefix}/events",
    'action' => function() {

      // Get the events pages
      $events = page('events')->children()->visible();
      $data = [];

      // Transform for API delivery
      foreach ($events as $event) {
        $data[] = $event->serialize();
      }

      return response::json($data);
    }
  ]

]);

?>

// controllers/events.php
<?php

return function ($site, $pages, $page) {
  if (get('format') == 'json') {
    $data = [
      'uid'   => $page->uid(),
      'title' => $page->title()->toString(),
      'text'  => (string) $page->kirbytext(),
    ];

    die(response::json($data, 200));
  }
}

?>

// models/event.php
<?php

class EventPage extends Page {
  public function serialize() {
    return [
      'uid'     => $this->uid(),
      'url'     => $this->url(),
      'title'   => $this->title()->html()->toString(),
      'text'    => $this->text()->kirbytext()->toString()
    ];
  }
}

?>

So visiting /api/v1/events you get a nice 200 status JSON response. Here’s my commit.

1 Like