Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

elliotk's avatar

How to consume an API

Hello,

I am looking for some pointers to good content on how to consume an API.

I have never consumed data from an API before, but my electricity provider gives electricity consumption in 30 minute intervals, so I want to put a project together to help my learning.

I call the API via Curl at the moment..

api-url.com/consumption/?period_from=2021-09-10T16:00:00Z&period_to=2021-09-10T16:30:00Z"

{
   "count":2,
   "next":null,
   "previous":null,
   "results":[
      {
         "consumption":0.713,
         "interval_start":"2021-09-10T17:30:00+01:00",
         "interval_end":"2021-09-10T18:00:00+01:00"
      },
      {
         "consumption":0.971,
         "interval_start":"2021-09-10T17:00:00+01:00",
         "interval_end":"2021-09-10T17:30:00+01:00"
      }
   ]
}

So if I want to store this data in my database what's the best way to do this?

  1. Create some kind of worker to call the API every 30 minutes?
  2. How do specify the time range to make sure no 30 minute interval is missed or are duplicated?
  3. How would you handle downtime on my server? Lets say it was offline for 2 hours? How does it go back and fill in the gaps?
  4. What about a failure on the api end - I presume you would some how re-queue the job?

If there is a good Laracasts video on this? Happy to watch through.

Thanks

0 likes
5 replies
goldeneye's avatar

You can use scheduler:

https://laravel.com/docs/8.x/scheduling#running-the-scheduler

just create command/job and set it in 30 mins intervals.

In case of failure your job can retry X times.

UPDATE:

2 - what about put 48 entries to the DB every day - and only update consumption every 30 minutes.

3 - in case of downtime you can also based on past rows without consumption update it as well

elliotk's avatar

So that solves 1 and 4

How do you handle 2 and 3?

nexxai's avatar
  1. Yes, create a schedule entry to run every 30 minutes, hitting the API, grabbing the data, and putting it into the database (as some "Consumption" model, or something)
  2. https://laravel.com/docs/8.x/scheduling#scheduling-queued-jobs - $schedule->job(new GetEnergyUsage, 'consumption', 'sqs')->everyThirtyMinutes();
  3. In the logic, have it check for the last known interval, then have it build any intervals that it would have missed
  4. Failed jobs can be configured to try again X times.

Please or to participate in this conversation.