4

I'm building a web with laravel that relies on an external API to get the data that I show to my users (http://eztvapi.re in my case). I'm using guzzle for the api calls and it works fine.

The API is very simple, it either displays a list of shows (with metadata for them) or the info of one show given its ID.

The problem comes when I need to show the info for, say, 15 given shows that a user has selected as favorite. That means I need to query the API 15 times, one for each shows, and that slows the web a lot (also it's too many requests for the API, that doesn't seem right to me).

Basically this:

foreach ($favorites as $fav) {
    $client = new Client();
    $res = $client->get('http://eztvapi.re/show/'.$fav->id);
    $show = $res->json(); 
}

I've considered copying to my database the contents of the api, but that defeats the purpose of connecting to the api altogether, and it would need to be updated very frequently. I thought maybe cache was the way to go but I'm not clear on how to approach that route, I searched for laravel cache and it seems it's only aimed to cache queries to the database (or maybe I didn't understand well the docs).

What would be the proper way for this?

3

1 Answer 1

4

Ok, thanks to Dexa's comment I got in the right track. I used https://github.com/RemiCollin/GuzzleCache (I had trouble setting it up at first but the dev helped me out).

On a page with 50 requests to the api I went from 20 seconds to 200ms.

This was my code at the end (the function is called for each show):

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

use \GuzzleHttp\Client;
use GuzzleCache;


class Show extends Model {

    /* .. other functions .. */

    public function getShowInfo(){
        $id = $this->imdb;

        $client = GuzzleCache::client(['base_url' => 'http://eztvapi.re']);

        $res = $client->get('http://eztvapi.re/show/'.$id);
        $show = $res->json();

        return $show;
    }

}

EDIT: This would be a good enough solution for some apis, but in my case this api is updated quite frequently, and the 20 seconds it takes to load when it's not being cached it's way too much and it'd happen to the user. So I'm not going to accept my own answer (without testing enough I thought it could be the solution but I don't think so anymore)

Sign up to request clarification or add additional context in comments.

1 Comment

I am also having trouble,, this doesnt work on my side. it still loads slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.