Move api endpoint creation from controller to router


#1

hi!

this is more of a can i do it simpler and more leaner kind of question:

i setup a controller (api.php) + template (api.php, api.json.php) + content/page (/api) to create an API endpoint where kirby is fetching some data from another external service. this all works.

i was wondering, and had some vague memories, that maybe this might be all possible to do by using only a router in config.php? or not?

  • if yes, is it allowed to call a php library from within config.php?
  • if not, then maybe i can still use a route and being able to ditch /template/api.php and /template/ap.json.php and only keep the controller?

thanks!
af


Load plugins if not visiting /panel page
#2

You can do it in a route, yes. But I wouldn’t put the route into the config.php but into a plugin. then you can have all your logic in the plugin. If you don’t have a template, then you don’t want to use a controller.


#3

in the attempt of avoiding to make a new post for this…

i moved the above controller inside a generic api/api.php kirby plugin but get an error now

Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in /www/public/site/plugins/api/api.php on line 3

Fatal error: require(): Failed opening required 'vendor/autoload.php' (include_path='.:') in /www/public/site/plugins/api/api.php on line 3

line 3 is the below require('vendor/autoload.php');

been trying to change the path from

require('vendor/autoload.php');
use \DrewM\MailChimp\MailChimp;

to

require('../../../vendor/autoload.php');

which is the correct relative path to go back to the vendor folder. i thought that maybe i should use kirby extension registry, but by checking that page it’s unlikely.

any hint?

following the whole plugin code

<?php

require('vendor/autoload.php');
use \DrewM\MailChimp\MailChimp;

kirby()->routes([
  [
    'method' => 'GET',
    'pattern' => 'newsletter',
    'action' => function() {
      if(r::is('POST')) {
        $mc_data = r::data();

        // mailchimp api
        $mc_apikey = page('newsletter')->apikey();
        $mc_listid = page('newsletter')->listid();

        $mc = new MailChimp($mc_apikey);

        // mc subscribe new user
        $response = $mc->post('lists/' . $mc_listid . '/members', [
          'email_address' => $mc_data['email'],
          'status' => 'pending',
          'double_optin' => true,
          'update_existing' => false,
          'send_welcome' => false
        ]);

        if ($mc->success()) {
          print_r($response);
        } else {
          echo $mc->getLastError();
        }

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

thanks!
af


#4
require_once(__DIR__.DS.'vendor'.DS.'autoload.php');

#5

thanks!

looks like the problem with using

require('vendor/autoload.php');

happens only when im accessing the /panel. so I’ll do a check for that before letting the rest of the code to happen…