Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching API Data Laravel 5.2

I'am working on the Halo 5 API. I applied to get a higher rate limit for the API, and one of the responses I got was this:

Can you please provide us more details about which calls you’re making to the APIs and if you’re using any caching? Specifically we would recommend caching match and event details and metadata as those rarely change.

I get the part when they say "which calls you're making", but the caching part, I have never worked with that. I get the basic parts of caching, that it speeds up your API, but I just wouldn't know how to implement it into my API.

I would want to know how to cache some data in my app. Here is a basic example of how I would get players medals from the API.

Route:

Route::group(['middleware' => ['web']], function () {

    /** Get the Home Page **/
    Route::get('/', 'HomeController@index');


    /** Loads ALL the player stats, (including Medals, for this example) **/
    Route::post('/Player/Stats', [
        'as' => 'player-stats',
        'uses' => 'StatsController@index'
    ]);

});

My GetDataController to call the API Header to get Players Medals:

<?php

namespace App\Http\Controllers\GetData;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;

use GuzzleHttp;
use App\Http\Controllers\Controller;

class GetDataController extends Controller {


    /**
     * Fetch a Players Arena Stats
     *
     * @param $gamertag
     * @return mixed
     */
    public function getPlayerArenaStats($gamertag) {

        $client = new GuzzleHttp\Client();

        $baseURL = 'https://www.haloapi.com/stats/h5/servicerecords/arena?players=' . $gamertag;

        $res = $client->request('GET', $baseURL, [
            'headers' => [
                'Ocp-Apim-Subscription-Key' => env('Ocp-Apim-Subscription-Key')
            ]
        ]);

        if ($res->getStatusCode() == 200) {
            return $result = json_decode($res->getBody());
        } elseif ($res->getStatusCode() == 404) {
            return $result = redirect()->route('/');
        }

        return $res;
    }

}

My MedalController to get the Medals from a Player:

<?php

namespace App\Http\Controllers;

use GuzzleHttp;
use App\Http\Controllers\Controller;

class MedalController extends Controller {



    public function getArenaMedals($playerArenaMedalStats) {

        $results = collect($playerArenaMedalStats->Results[0]->Result->ArenaStats->MedalAwards);

        $array = $results->sortByDesc('Count')->map(function ($item, $key) {
            return [
                'MedalId' => $item->MedalId,
                'Count' => $item->Count,
            ];
        });

        return $array;
    }


}

And this is the function to display the Players medals into view:

 public function index(Request $request) {

        // Validate Gamer-tag
        $this->validate($request, [
            'gamertag' => 'required|max:16|min:1',
        ]);

        // Get the Gamer-tag inserted into search bar
        $gamertag = Input::get('gamertag');




        // Get Players Medal Stats for Arena
        $playerArenaMedalStats = app('App\Http\Controllers\GetData\GetDataController')->getPlayerArenaStats($gamertag);
        $playerArenaMedalStatsArray = app('App\Http\Controllers\MedalController')->getArenaMedals($playerArenaMedalStats);
        $arenaMedals = json_decode($playerArenaMedalStatsArray, true);



         return view('player.stats')
            ->with('arenaMedals', $arenaMedals)

}

Would you guys know how to cache this data?

(FYI, there are about 189 different medals from the JSON call, so its a pretty big API call). I also read the documentation about caching for Laravel, but still need clarification.

like image 619
David Avatar asked May 10 '16 18:05

David


People also ask

How do I enable caching in Laravel?

To enable Laravel caching services, first use the Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository, as they provide access to the Laravel caching services. The Factory contract gives access to all the cache drivers of your application.

Does Laravel have caching?

Laravel supports popular caching backends like Memcached, Redis, DynamoDB, and relational databases out of the box. In addition, a file based cache driver is available, while array and "null" cache drivers provide convenient cache backends for your automated tests.

Can we cache in REST API?

Caching REST APIs offers so many benefits: It improves response times: When a client repeatedly initiates an API without caching instructions, the API's response time is the same whether or not the data changes or not.


1 Answers

You could use Laravel Cache.

Try this:

public function getPlayerArenaStats($gamertag) {
.... some code ....
    $res = $client->request('GET', $baseURL, [
        'headers' => [
            'Ocp-Apim-Subscription-Key' => env('Ocp-Apim-Subscription-Key')
        ]
    ]);
    Cache::put('medals', $res, 30); //30 minutes
    .... more code...
}

public function index(Request $request) {
...
if (Cache::has('medals')) {
    $playerArenaMedalStats = Cache::get('medals');
} else {
    app('App\Http\Controllers\GetData\GetDataController')->getPlayerArenaStats($gamertag);
}
...

Of course, you will need to do better than this, to store only the information you need. Check the docs here: https://laravel.com/docs/5.1/cache

like image 194
Felippe Duarte Avatar answered Oct 02 '22 03:10

Felippe Duarte