Taking data from the API Response and putting it into kirby text file

Hello guys, I’m still very new to all of this, what is the easiest way to take the json response, take a piece out of it, and save it in the text file that stores the rest of the page’s dynamic content.

Can I do this with Kirby Hooks? or…

Thanks - Josh :slight_smile: :slightly_smiling_face:

I guess you are talking about fetching data from an external API and storing this as Kirby pages or as part of Kirby pages? A hook is probably not the right way to do this, because a hook is called as a reaction to some event, like creating or updating a page, file etc., but depends on your exact use case.

Instead you can use a route, or trigger a script via a Janitor button, but again, if you are more specific about what you want to achieve, we can probably help better.

The external API I am using basically calculates finance, so for each car I POST to the API a bunch of vehicle details and it returns me the amount per month. I need to display this per month price on the page, and in the foreach loop that will list all of the vehicles…

I don’t want to run this API 100s of times as someone browses the site, so I just want my client to be able to save the page, and it automatically runs the API POST and stores that single piece of data from the response json in the kirby page.

So you need the data whenever you update the vehicle? Then a page.update:after hook could be the right choice.

Yes unless you know how I could do this better? I basically want to avoid calling the API over and over when I can just do it once and store the value :slight_smile:

So you only need the information once per vehicle? And the POST request is always the same for each vehicle, only the data you send via the request is different? Then maybe use a route with a placeholder for the vehicle that you can call manually. Again, you know best what you have to do and how far you want to automate.

It needs to run as the page saves, because if the vehicle data changes, especially the price, the finance price will change so I think using the hook will be the best then? Would you agree?

But then how to take that data, and send it to the text file is what I don’t know how to do in that case


In the hook, you make your request to the API, wait for the response, and then call $page->update() to update the page data with the data from the response.

1 Like