Hi everyone, I’m new to working with APIs in Kirby and have run into a few issues.
What I’m trying to achieve:
- Make an API call to an external service
- Reassemble the necessary data
- Display the data as cards inside a component/snippet wherever it’s used on the website. The cards will not have any further interaction. Just displaying the data.
- Side info: the data will update daily. So it will have to make an API call once a day.
I followed this guide: Content from an API.
My questions:
- Based on the guide, I would create a page model and save the API data as children of a Page. But is this the best approach for my component? I’m not sure if this logic should go inside the config, a hook, or somewhere else. Using children feels a bit odd, but maybe that’s the way to go?
- I’ve successfully fetched and structured my data, but I’m getting confused between Kirby objects and standard arrays. What’s the best way to handle JSON data in Kirby? What format should I use?
Here’s some code:
Making the API call and structuring the data:
$response = Remote::request($api, [
'method' => 'GET',
'headers' => [
'X-API-Key' . $password,
'Authorization: Basic ' . base64_encode("$username:$password")
],
]);;
if ($response->code() === 200) {
$data = $response->json(true);
}
$result = [];
foreach ($data['rows']['cards'] as $card) {
$version = $card['items']['version']['title'] ?? null;
if ($version) {
$result[$version]['cards']["en"][] = [
'id' => $card["id"],
'title' => $card['item']['en']['title'],
'text' => $card['item']['en']['desc'],
];
$result[$version]['cards']["fr"][] = [
'id' => $card["id"],
'title' => $card['item']['fr']['title'],
'text' => $card['item']['fr']['desc'],
];
}
}
foreach ($result as $key => $data) {
$pages[] = [
'template' => 'cards',
'slug' => "version-" . $key,
'model' => 'cards',
'content' => [
'version' => $key,
'data' => $data,
'uuid' => Uuid::generate(),
]
];
}
Inside the snippet:
when I print the data inside my snipped it gives me this format:
Kirby\Content\Field Object
(
[data] => Array
(
[cards] => Array
(
[fr] => Array
(
[0] => Array
(
[id] => 154
[title] => Lorem Ipsum
[text] => Lorem Ipsum
)
)
[en] => Array
(
[0] => Array
(
[id] => 154
[title] => Lorem Ipsum
[text] => Lorem Ipsum
)
)
)
)
)
How do I print this? Nothing I tried worked… for example:
$item->data()["cards"]["fr"]
Help is much appreciated!