Robust PHP API Gateway with API key authentication, client rate limiting, response caching, and flexible external endpoint configurations for enhanced performan
<?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();
?>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