PHP API Gateway with Client Rate Limiting, Response Caching, and API Key Management

Robust PHP API Gateway with API key authentication, client rate limiting, response caching, and flexible external endpoint configurations for enhanced performan

Brief Introduction

PHP API Gateway with Client Rate Limiting, Response Caching, and API Key Management (php)
DESCRIPTION:
Implementation of a robust PHP API gateway that handles authentication via API key, limits requests per client to prevent abuse, caches responses to improve performance, and offers flexible configurations for external endpoints.

ADDITIONAL NOTES:
The code is ready to use in a PHP environment with SQLite. Just configure the database file and API keys in the database. The system is extendable to support other authentication methods or storage.

EXPLANATIONS:
- The ApiGateway class manages all functionalities: authentication, rate limiting, caching, and request forwarding.
- The authenticate method verifies the presence and validity of the API key passed in the 'X-API-Key' header.
- Rate limiting checks how many requests have been made in the last minute and blocks if the configured limit is exceeded.
- Caching saves the response of external calls for a configurable time to reduce latency and load.
- External requests are forwarded via cURL with error handling and timeout.
- SQLite database is used for simplicity and portability but can be replaced with MySQL or other DBs.
- The code is commented in Italian to facilitate understanding and maintenance.

Example Code: php

<?php
/**
 * PHP API Gateway with rate limiting, caching, and API key management
 *
 * Features:
 * - Authentication via API key
 * - Rate limiting per client (requests per minute)
 * - Caching of external API responses
 * - External endpoints configuration
 *
 * Requirements:
 * - PHP 7.4+ with PDO and SQLite
 *
 * SQLite database structure (file: data/api_gateway.sqlite):
 *
 * CREATE TABLE api_keys (
 *   key TEXT PRIMARY KEY,
 *   client_name TEXT NOT NULL,
 *   active INTEGER NOT NULL DEFAULT 1,
 *   rate_limit_per_minute INTEGER NOT NULL DEFAULT 60
 * );
 *
 * CREATE TABLE rate_limits (
 *   key TEXT NOT NULL,
 *   window_start INTEGER NOT NULL,
 *   count INTEGER NOT NULL,
 *   PRIMARY KEY(key, window_start)
 * );
 *
 * CREATE TABLE cache (
 *   cache_key TEXT PRIMARY KEY,
 *   response TEXT NOT NULL,
 *   expires_at INTEGER NOT NULL
 * );
 */

class ApiGateway {
    private PDO $db;
    private array $config;

    public function __construct(string $dbPath, array $config = []) {
        // Connect to SQLite database
        $this->db = new PDO('sqlite:' . $dbPath);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Default configurations
        $this->config = array_merge([
            'cache_ttl_seconds' => 60, // cache duration in seconds
            'default_rate_limit' => 60, // requests per minute if not specified
            'external_endpoints' => [
                // example external endpoint
                'example' => [
                    'url' => 'https://jsonplaceholder.typicode.com/posts',
                    'methods' => ['GET'],
                    'timeout' => 5
                ]
            ]
        ], $config);
    }

    /**
     * Main method to handle the request
     */
    public function handleRequest(): void {
        try {
            // Retrieve API key from header
            $apiKey = $this->getApiKeyFromHeaders();
            if (!$apiKey) {
                $this->sendResponse(401, ['error' => 'Missing API key']);
                return;
            }

            // Authenticate API key
            $apiKeyData = $this->authenticate($apiKey);
            if (!$apiKeyData) {
                $this->sendResponse(403, ['error' => 'Invalid or disabled API key']);
                return;
            }

            // Check rate limiting
            if (!$this->checkRateLimit($apiKey, (int)$apiKeyData['rate_limit_per_minute'])) {
                $this->sendResponse(429, ['error' => 'Request limit exceeded']);
                return;
            }

            // Parse URI for endpoint
            $endpointKey = $this->parseEndpointKey();
            if (!$endpointKey || !isset($this->config['external_endpoints'][$endpointKey])) {
                $this->sendResponse(404, ['error' => 'Endpoint not found']);
                return;
            }

            $endpointConfig = $this->config['external_endpoints'][$endpointKey];

            // Verify HTTP method
            $method = $_SERVER['REQUEST_METHOD'];
            if (!in_array($method, $endpointConfig['methods'])) {
                $this->sendResponse(405, ['error' => 'HTTP method not allowed']);
                return;
            }

            // Generate cache key
            $cacheKey = $this->generateCacheKey($endpointKey, $method, $_GET, file_get_contents('php://input'));

            // Check cache
            $cachedResponse = $this->getCachedResponse($cacheKey);
            if ($cachedResponse !== null) {
                $this->sendResponse(200, json_decode($cachedResponse, true), true);
                return;
            }

            // Forward request to external endpoint
            $response = $this->forwardRequest($endpointConfig['url'], $method, $_GET, file_get_contents('php://input'), $endpointConfig['timeout']);

            if ($response === false) {
                $this->sendResponse(502, ['error' => 'Error communicating with external endpoint']);
                return;
            }

            // Save response in cache
            $this->cacheResponse($cacheKey, $response, $this->config['cache_ttl_seconds']);

            // Send response to client
            $this->sendResponse(200, json_decode($response, true));

        } catch (Exception $e) {
            error_log('ApiGateway error: ' . $e->getMessage());
            $this->sendResponse(500, ['error' => 'Internal server error']);
        }
    }

    /**
     * Retrieve API key from HTTP headers
     *
     * @return string|null
     */
    private function getApiKeyFromHeaders(): ?string {
        $headers = getallheaders();
        return $headers['X-API-Key'] ?? null;
    }

    /**
     * Authenticate the API key in the database
     *
     * @param string $key
     * @return array|null
     */
    private function authenticate(string $key): ?array {
        $stmt = $this->db->prepare('SELECT * FROM api_keys WHERE key = :key AND active = 1');
        $stmt->execute([':key' => $key]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ?: null;
    }

    /**
     * Check and update rate limiting for the API key
     *
     * @param string $key
     * @param int $limit
     * @return bool true if under limit, false if exceeded
     */
    private function checkRateLimit(string $key, int $limit): bool {
        $currentWindow = floor(time() / 60); // 1-minute window

        // Begin transaction to avoid race condition
        $this->db->beginTransaction();

        // Retrieve rate limit record
        $stmt = $this->db->prepare('SELECT count FROM rate_limits WHERE key = :key AND window_start = :window');
        $stmt->execute([':key' => $key, ':window' => $currentWindow]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            if ($row['count'] >= $limit) {
                $this->db->rollBack();
                return false; // limit exceeded
            }
            // Increment counter
            $stmt = $this->db->prepare('UPDATE rate_limits SET count = count + 1 WHERE key = :key AND window_start = :window');
            $stmt->execute([':key' => $key, ':window' => $currentWindow]);
        } else {
            // Insert new record
            $stmt = $this->db->prepare('INSERT INTO rate_limits (key, window_start, count) VALUES (:key, :window, 1)');
            $stmt->execute([':key' => $key, ':window' => $currentWindow]);
        }

        $this->db->commit();
        return true;
    }

    /**
     * Extract endpoint key from URI
     *
     * Example: /api/example -> 'example'
     *
     * @return string|null
     */
    private function parseEndpointKey(): ?string {
        $uri = $_SERVER['REQUEST_URI'];
        $path = parse_url($uri, PHP_URL_PATH);
        $parts = explode('/', trim($path, '/'));

        // Assume structure /api/{endpoint}
        if (count($parts) >= 2 && $parts[0] === 'api') {
            return $parts[1];
        }
        return null;
    }

    /**
     * Generate a unique cache key based on endpoint, method, and parameters
     *
     * @param string $endpoint
     * @param string $method
     * @param array $queryParams
     * @param string $body
     * @return string
     */
    private function generateCacheKey(string $endpoint, string $method, array $queryParams, string $body): string {
        ksort($queryParams); // sort for consistency
        $data = $endpoint . '|' . $method . '|' . http_build_query($queryParams) . '|' . $body;
        return hash('sha256', $data);
    }

    /**
     * Retrieve response from cache if valid
     *
     * @param string $cacheKey
     * @return string|null
     */
    private function getCachedResponse(string $cacheKey): ?string {
        $stmt = $this->db->prepare('SELECT response, expires_at FROM cache WHERE cache_key = :key');
        $stmt->execute([':key' => $cacheKey]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row && $row['expires_at'] >= time()) {
            return $row['response'];
        }

        // Cache expired or not present
        if ($row) {
            // Delete expired cache
            $stmt = $this->db->prepare('DELETE FROM cache WHERE cache_key = :key');
            $stmt->execute([':key' => $cacheKey]);
        }

        return null;
    }

    /**
     * Save response in cache
     *
     * @param string $cacheKey
     * @param string $response
     * @param int $ttl_seconds
     * @return void
     */
    private function cacheResponse(string $cacheKey, string $response, int $ttl_seconds): void {
        $expiresAt = time() + $ttl_seconds;
        $stmt = $this->db->prepare('REPLACE INTO cache (cache_key, response, expires_at) VALUES (:key, :response, :expires)');
        $stmt->execute([
            ':key' => $cacheKey,
            ':response' => $response,
            ':expires' => $expiresAt
        ]);
    }

    /**
     * Forward HTTP request to external endpoint
     *
     * @param string $url
     * @param string $method
     * @param array $queryParams
     * @param string $body
     * @param int $timeout
     * @return string|false
     */
    private function forwardRequest(string $url, string $method, array $queryParams, string $body, int $timeout) {
        $ch = curl_init();

        // Build URL with query string
        if (!empty($queryParams)) {
            $url .= '?' . http_build_query($queryParams);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        // HTTP method
        switch ($method) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
                break;
            case 'PUT':
            case 'PATCH':
            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
                break;
            case 'GET':
            default:
                // GET has no body
                break;
        }

        // Headers
        $headers = ['Accept: application/json'];
        if (in_array($method, ['POST', 'PUT', 'PATCH'])) {
            $headers[] = 'Content-Type: application/json';
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            error_log('cURL error: ' . curl_error($ch));
            curl_close($ch);
            return false;
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 200 && $httpCode < 300) {
            return $response;
        }

        error_log('External endpoint HTTP code: ' . $httpCode);
        return false;
    }

    /**
     * Send JSON response to client
     *
     * @param int $statusCode
     * @param array $data
     * @param bool $fromCache
     * @return void
     */
    private function sendResponse(int $statusCode, array $data, bool $fromCache = false): void {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        if ($fromCache) {
            header('X-Cache: HIT');
        } else {
            header('X-Cache: MISS');
        }
        echo json_encode($data);
    }
}

// Usage example
// Assume SQLite file is in data/api_gateway.sqlite
// and tables are already created and populated

$gateway = new ApiGateway(__DIR__ . '/data/api_gateway.sqlite', [
    'cache_ttl_seconds' => 120,
    'external_endpoints' => [
        'example' => [
            'url' => 'https://jsonplaceholder.typicode.com/posts',
            'methods' => ['GET'],
            'timeout' => 5
        ]
    ]
]);

$gateway->handleRequest();

?>
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

PHP 7.4+ with PDO extension for SQLite database access

SQLite database to store API keys, rate limiting limits, and cached responses

API key management configuration: 'api_keys' table with key, client name, status (active/disabled), requests per minute limit

Rate limiting implemented via 'rate_limits' table with timestamp and request counter per API key

External API response caching via 'cache' table with hash key, serialized response, and expiration timestamp

External endpoints configured in a PHP array with URL, supported methods, and timeout

Simple routing management based on URI and HTTP method

Error logging to log file

Arduino wiring/pinout configuration not applicable in this software context

Software dependencies: no external libraries, only native PHP and PDO

PHP configuration file for global parameters (e.g., cache duration, default rate limit)

Folder structure: /src for code, /logs for logs, /data for SQLite database

Similar Topics

First PHP script: display a message on the screen
Learn how to create your first PHP script that displays a welcome message on the screen. Perfect for beginners to see immediate results with PHP code.
PHP page displaying the current date and time
Simple PHP script displaying current date and time in day/month/year hour:minute:second format with timezone settings for accurate local time display.
Very Simple Calculator with Two Numbers in PHP
A very simple PHP calculator script that adds two user-entered numbers via an HTML form and displays the result on the same page securely and efficiently.
PHP Form that Greets the User by Name
Simple PHP form that greets users by name using POST method with secure input handling and beginner-friendly code in a single PHP file.
PHP page that counts how many times it has been visited
Simple PHP script that counts and displays the number of visits to a web page using a writable text file to store the counter value securely.
Static product list displayed with PHP
Simple PHP example displaying a static product list with name description and price using arrays and foreach loop for beginners learning PHP.
PHP page that generates an HTML table from an array
Learn how to create a simple PHP page that dynamically generates an HTML table from a multidimensional array with secure and easy to understand code.
Mini address book in PHP with a contacts array
A simple PHP mini address book script using an array to display and search contacts by name with case insensitive search and no database needed.