gCore

APIManager Documentation

Overview

The APIManager serves as the core REST API interface for the gCore framework, providing a high-performance, scalable, and secure API gateway with built-in middleware support, request processing, caching, rate limiting, and authentication. It integrates transparently with ValKey/Redis for distributed operations while maintaining zero external dependencies to prevent circular dependency issues.

Key Features

Architecture

The APIManager follows gCore's modular trait-based architecture:

Core Module

Traits

Server Modes

The APIManager supports multiple server operation modes:

  1. Auto Mode (default): Automatically selects the appropriate mode based on environment

    • In CLI: Starts PHP's built-in server
    • In web server: Integrates with existing web server
    • In test environments: Skips server startup
  2. Standalone Mode: Forces use of PHP's built-in server

    • Ideal for development and testing
    • Configurable host and port
  3. Integrated Mode: Integrates with existing web server

    • Optimized for production environments with Apache/Nginx
    • Uses existing web server's routing
  4. Disabled Mode: Prevents server startup

    • For applications that need the API structure but handle HTTP requests differently

Getting Started

Basic Usage

// Get APIManager instance
$apiManager = gcore_get_api_manager();

// Initialize with configuration
$apiManager->initialize([
    'server' => [
        'mode' => 'standalone',
        'port' => 8080,
        'host' => '127.0.0.1'
    ]
]);

// Add middleware for authentication
$apiManager->addMiddleware('auth', function($request, $response, $next) {
    $apiKey = $request->getHeader('X-API-Key');
    if (!$this->validateAPIKey($apiKey)) {
        return $response->json(['error' => 'Unauthorized'], 401);
    }
    return $next($request, $response);
});

// Register endpoint with URL parameter
$apiManager->registerEndpoint('GET', '/users/:id', function($request, $response) {
    $userId = $request->getParam('id');
    $user = getUserById($userId);
    return $response->json($user);
}, [
    'middleware' => ['auth'],
    'cache' => true
]);

// Start the server
$apiManager->start();

Request Handling

The APIManager provides request and response objects for handling HTTP interactions:

// Request object methods
$method = $request->getMethod();       // GET, POST, etc.
$path = $request->getPath();           // Request path
$query = $request->getQuery();         // Query parameters
$body = $request->getBody();           // Request body
$json = $request->getJson();           // JSON parsed body
$header = $request->getHeader('Name'); // Request header
$param = $request->getParam('id');     // Path parameter

// Response object methods
$response->setStatus(200);                   // Set status code
$response->setHeader('X-Custom', 'value');   // Set header
$response->json(['data' => $value]);         // JSON response
$response->html('<html>...</html>');         // HTML response
$response->text('Plain text');               // Text response
$response->file('/path/to/file');            // File response
$response->redirect('/new-location');        // Redirect

Advanced Features

Middleware Pipeline

The middleware pipeline allows processing requests through a series of handlers:

// Rate limiting middleware
$apiManager->addMiddleware('rate-limit', function($request, $response, $next) {
    $clientId = $request->getClientIp();
    $route = $request->getPath();

    if ($this->isRateLimited($clientId, $route)) {
        return $response->json([
            'error' => 'Rate limit exceeded'
        ], 429);
    }

    // Add rate limit headers
    $response = $next($request, $response);
    $limits = $this->getRateLimitHeaders($clientId, $route);

    foreach ($limits as $name => $value) {
        $response->setHeader($name, $value);
    }

    return $response;
});

// Apply middleware to endpoint
$apiManager->registerEndpoint('GET', '/data', $handler, [
    'middleware' => ['auth', 'rate-limit']
]);

URL Parameter Extraction

The APIManager supports path parameters with regex pattern matching:

// Basic parameter
$apiManager->registerEndpoint('GET', '/users/:id', $handler);

// With regex constraint
$apiManager->registerEndpoint('GET', '/users/:id([0-9]+)', $handler);

// Multiple parameters
$apiManager->registerEndpoint('GET', '/posts/:year/:month/:slug', $handler);

// Optional parameters
$apiManager->registerEndpoint('GET', '/articles/:category?', $handler);

Response Caching

Cache API responses for improved performance:

// Enable response caching
$apiManager->initialize([
    'cache' => [
        'enabled' => true,
        'ttl' => 300, // 5 minutes
        'exclude' => ['/users/profile'] // Routes to exclude
    ]
]);

// Register cacheable endpoint
$apiManager->registerEndpoint('GET', '/products', $handler, [
    'cache' => true,
    'cache_ttl' => 600 // 10 minutes
]);

// Clear cache for a route
$apiManager->clearResponseCache('/products');

API Authentication

Multiple authentication methods:

// API key authentication
$apiManager->registerAuthMethod('api-key', function($request) {
    $key = $request->getHeader('X-API-Key');
    return $this->validateAPIKey($key);
});

// JWT authentication
$apiManager->registerAuthMethod('jwt', function($request) {
    $token = $request->getHeader('Authorization');
    if (empty($token) || strpos($token, 'Bearer ') !== 0) {
        return false;
    }
    $token = substr($token, 7);
    return $this->validateJWT($token);
});

// Register endpoint with auth
$apiManager->registerEndpoint('GET', '/secure-data', $handler, [
    'auth' => 'api-key'
]);

Rate Limiting

Control request rates to prevent abuse:

// Configure rate limiting
$apiManager->initialize([
    'rate_limiting' => [
        'enabled' => true,
        'default_limit' => 60, // per minute
        'routes' => [
            '/api/search' => 30,
            '/api/upload' => 10
        ]
    ]
]);

// Get rate limit status
$status = $apiManager->getRateLimitStatus($clientId, $route);

API Digest

Main APIManager Class (gCore\Modules\Managers\Base\APIManager\APIManager)

EndpointManagerTrait

RequestProcessorTrait

ResponseCacheTrait

RateLimiterTrait

AuthenticationTrait

ValidationTrait

MetricsCollectorTrait

Best Practices

  1. Use Middleware for Cross-Cutting Concerns

    • Authentication, logging, rate limiting, etc.
    • Keep endpoint handlers focused on business logic
  2. Use Response Caching

    • Cache read-heavy endpoints
    • Set appropriate TTLs based on data volatility
  3. Implement Proper Rate Limiting

    • Adjust limits based on endpoint impact
    • Use different limits for authenticated vs. anonymous requests
  4. Structure API Endpoints Logically

    • Use RESTful patterns for resources
    • Group related endpoints
  5. Validate All Input

    • Define validation schemas for endpoints
    • Use custom validators for complex validation
  6. Collect and Monitor Metrics

    • Track response times and error rates
    • Export metrics for monitoring systems
  7. Choose the Right Server Mode

    • Use standalone for development
    • Use integrated for production
    • Use auto for adaptive behavior

Performance Considerations

Security Considerations

Troubleshooting

Common Issues

  1. Server won't start

    • Check port availability
    • Verify permissions
    • Check server mode configuration
  2. Authentication failures

    • Verify API key format and validity
    • Check auth method registration
  3. Rate limiting problems

    • Check rate limit configuration
    • Verify client identification method
  4. Path parameter extraction issues

    • Check path pattern format
    • Verify regex patterns if used

Conclusion

The APIManager provides a flexible and flexible foundation for building APIs with gCore. Its modular design, middleware support, and integrated server capabilities make it suitable for a wide range of applications from simple services to complex APIs.


Updated: March 2025