Virtual Pages with API and Caching

content() returns a string.
Therefore you can’t call ->json() on it. You would have to call ->json() on the $response (an instance of the Remote class); but actually, since both the cache and the API call give you strings, it’s easier to just use something like PHPs json_decode on the result of either one.

If you are using Kirby 3.8 or later, we can use $cache->getOrSet() to make the code a bit more concise.
I’d refactor the code like this:

    public function children() {
        $pages = [];

        $apiData = kirby()
            ->cache('api')
            ->getOrSet('apiData', fn() => $this->fetchData(), 720);
     
        $apiData = json_decode($apiData);
        $corsi = $apiData->corsi;

        foreach ($corsi as $key => $review) {
            $pages[] = [
                'slug'     => Str::slug($review->titolo),
                'num'      => $key+1,
                'template' => 'review',
                'model'    => 'review',
                'content'  => [
                    'title'    => $review->titolo,
                    'headline' => $review->sottotitolo,
                    'byline'   => $review->codice,
                    'summary'  => $review->sedeCorso,
                    'date'     => $review->datainizio,
                    'link'     => $review->allegati,
                    'linkText' => $review->destinatari,
                    'cover'    => $review->urlImmagine
                ]
            ];
        }

        return Pages::factory($pages, $this);
    }

    public function fetchData(): string {
        $apiKey  = '';
        $user = 'myUser';
        $password = 'MyPassword';

        $response = Remote::get('https://api.website.com/thefile.json', [
            'headers' => [
                'Authorization: Basic ' . base64_encode($user . ':' . $password)
            ]
        ]);

        if ($response->code() === 200) {
            return $response->content();
        }

        //@todo: handle error case better than this
        throw "Could not fetch data";
    }

4 Likes