PHP

Optimize External API Calls with Server-Side Caching (Laravel)

Improve application responsiveness and reduce repeated calls to external APIs by implementing a server-side caching strategy for frequently accessed data.

<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Exception;

class ExternalApiService
{
    protected $baseUrl;
    protected $cacheTtl; // Time To Live in seconds for cache

    public function __construct()
    {
        $this->baseUrl = config('services.external_api.url');
        $this->cacheTtl = config('services.external_api.cache_ttl', 3600); // Default 1 hour
    }

    /**
     * Fetches data from an external API, with caching.
     *
     * @param string $endpoint The API endpoint (e.g., 'products/123').
     * @param array $queryParameters Query parameters to append.
     * @param bool $forceRefresh Whether to bypass cache and fetch fresh data.
     * @return array|null
     */
    public function fetchData(string $endpoint, array $queryParameters = [], bool $forceRefresh = false): ?array
    {
        $cacheKey = 'external_api:' . md5($endpoint . serialize($queryParameters));

        if (!$forceRefresh && Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }

        try {
            $response = Http::withHeaders([
                'Accept' => 'application/json',
                // Add any necessary authentication headers here, e.g., 'Authorization' => 'Bearer ' . $this->getToken()
            ])->get("{$this->baseUrl}/{$endpoint}", $queryParameters);

            if ($response->successful()) {
                $data = $response->json();
                Cache::put($cacheKey, $data, $this->cacheTtl);
                return $data;
            } else {
                // Log error, throw exception, or return default
                logger()->error('External API request failed', [
                    'endpoint' => $endpoint,
                    'status' => $response->status(),
                    'response' => $response->body()
                ]);
                return null;
            }
        } catch (Exception $e) {
            logger()->error('Error fetching from external API', [
                'endpoint' => $endpoint,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    // Example usage in a controller or other service:
    // public function showProduct(string $productId)
    // {
    //     $apiService = new ExternalApiService();
    //     $productData = $apiService->fetchData("products/{$productId}");
    //     if ($productData) {
    //         // ... do something with productData
    //     }
    // }
}
How it works: This PHP (Laravel) snippet demonstrates a service-oriented approach to fetching data from external APIs with built-in server-side caching. It uses Laravel's `Http` client to make requests and the `Cache` facade to store and retrieve responses. A unique cache key is generated for each request based on the endpoint and query parameters, ensuring that subsequent identical requests retrieve data from the cache, reducing API calls and improving performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs