Web; code

Graphic design; video

[updated: ]

Caching HTTP requests with Laravel 5.5 and Guzzle 6

While working on a Laravel project in which repeated HTTP requests are made against several APIs, I needed a simple and unobtrusive way to cache the multiple API responses for some time — a time to live (TTL) specific for each API.

The project has a wrapper interface around Guzzle's ClientInterface and each implementation of the former corresponds to one of the APIs the project is talking to. This way I can manage all the requests in a likely fashion, while taking care of the specifics of each API. I can, for example, instantiate the below GuzzleResponseCache with a specific TTL.

The GuzzleResponseCache class is a Guzzle middleware, which means that it handles the intermediary execution of a handler, i.e. a function that modifies the request options and response of the HTTP request performed by Guzzle.

To make it work the GuzzleResponseCache middleware needs to be added to a handler stack, which will be traversed while doing the request. Like so:

$guzzleHandlerStack = \GuzzleHttp\HandlerStack:create();
$cache = \Illuminate\Support\Facades\Cache::store('database');
$guzzleHandlerStack->push(new GuzzleResponseCache($cache, 86400));
$client = new \GuzzleHttp\Client([
    handler => $guzzleHandlerStack
]);


This will cache all requests done with $client for 24 hours in the database — making use of Laravel's Cache facade (provided you have migrated a cache table with artisan).

News; blog