Fetch from API in Vue component

Am i right in thinking if you do something like:

let response = await this.$api.get("whatever");

in a panel plugin, it does not need authantication, because its the panel making the call? im a route that in the config that in turn calls a custom api to get to to display in the panel. Keep getting a 401 unauthorised.

I’m pretty sure that worked fine in my Snipcart plugin but now using kirby 4 on a different plugin, wondering if something has changed.

That should handle the authentication with the API, yes. But I think we will need to see the other side as well (your custom API route).

Ok so basically building a dashboard inside a custom panel area that gets data from the NinjaOne API. Authenticating with NinjaOne requires a token exchange.

So the route in the config looks like this:

  'api' => [
    'routes' => [
      [
        'pattern' => 'ninjaone/(:all)',
        'action'  => function ($param) {

          $ninjaone = [];

          $response = Remote::request('https://app.ninjarmm.com/v2/queries/' . $param, [
            'method' => 'GET',
            'headers' => [
              'Accept' => 'application/json',
              'Authorization' => 'Bearer ' . site()->getToken(),
            ],
          ]);
          if ($response->code() === 200) {
            $ninjaone = $response->json();
          };

          return $ninjaone;
        }
      ]
    ]
  ]

I have a site method that gets the token and returns it to the authorisation header. All that works if i just do it “raw” in template file. Trying to clean it up and do it sensibly. When i access the custom panel area, Kirby whirrs for a second and then throws and an unauthorised. The tokens have a life of one hour.

Its basically a dashboard that shows which computers are running old software… which are running out of disk space etc. Itll involve charts and tables and stuff eventually but for now just trying to get some data in to the Vue component and go from there.

And have you tried removing the extra API call from the route and to just return some dummy content? To see if then the communication between your JS code and the API route generally works?

OK so i just took the second api call out of the route and just returned a string from the route, and im still hitting a 401 unuthorised. Using Kirby 5 now

OK figured it out. Im not working alone on this project, seems there was a die statement added somehere in the code which was breaking it :man_facepalming: