ipoalerts Logoipoalerts
Quick Start Examples

PHP Examples

Quick start examples for integrating with the API using PHP

This page provides practical Quick start examples for integrating with the API using PHP.

Basic Client

<?php

class IPOAlertsClient {
    private $apiKey;
    private $baseUrl = 'https://api.ipoalerts.in';
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }
    
    private function makeRequest($endpoint, $method = 'GET', $data = null) {
        $url = $this->baseUrl . $endpoint;
        
        $headers = [
            'x-api-key: ' . $this->apiKey,
            'Content-Type: application/json'
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            }
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode >= 400) {
            throw new Exception("HTTP error: $httpCode - $response");
        }
        
        return json_decode($response, true);
    }
    
    public function getIPOs($filters = []) {
        $params = http_build_query($filters);
        $endpoint = '/ipos' . ($params ? '?' . $params : '');
        return $this->makeRequest($endpoint);
    }
    
    public function getIPO($identifier) {
        return $this->makeRequest("/ipos/$identifier");
    }
}

// Usage
$client = new IPOAlertsClient('YOUR_API_KEY');

try {
    $ipos = $client->getIPOs(['status' => 'upcoming', 'type' => 'EQ']);
    echo "Found " . $ipos['meta']['count'] . " upcoming equity IPOs\n";
    
    foreach ($ipos['ipos'] as $ipo) {
        echo $ipo['name'] . " (" . $ipo['symbol'] . ") - " . $ipo['priceRange'] . "\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Advanced Client with Caching

<?php

class AdvancedIPOAlertsClient extends IPOAlertsClient {
    private $cache = [];
    private $cacheDuration = 300; // 5 minutes
    private $requestCount = 0;
    private $lastRequestTime = 0;
    private $rateLimitDelay = 10; // 10 seconds between requests
    
    public function __construct($apiKey) {
        parent::__construct($apiKey);
    }
    
    private function getCacheKey($endpoint, $params = []) {
        return md5($endpoint . serialize($params));
    }
    
    private function isCacheValid($cacheKey) {
        if (!isset($this->cache[$cacheKey])) {
            return false;
        }
        
        $cachedTime = $this->cache[$cacheKey]['time'];
        return (time() - $cachedTime) < $this->cacheDuration;
    }
    
    private function enforceRateLimit() {
        $currentTime = time();
        $timeSinceLastRequest = $currentTime - $this->lastRequestTime;
        
        if ($timeSinceLastRequest < $this->rateLimitDelay) {
            $sleepTime = $this->rateLimitDelay - $timeSinceLastRequest;
            sleep($sleepTime);
        }
        
        $this->lastRequestTime = time();
    }
    
    public function getIPOs($filters = []) {
        $cacheKey = $this->getCacheKey('/ipos', $filters);
        
        if ($this->isCacheValid($cacheKey)) {
            echo "Returning cached data\n";
            return $this->cache[$cacheKey]['data'];
        }
        
        $this->enforceRateLimit();
        $result = parent::getIPOs($filters);
        
        $this->cache[$cacheKey] = [
            'data' => $result,
            'time' => time()
        ];
        
        return $result;
    }
    
    public function getIPO($identifier) {
        $cacheKey = $this->getCacheKey("/ipos/$identifier");
        
        if ($this->isCacheValid($cacheKey)) {
            echo "Returning cached IPO data\n";
            return $this->cache[$cacheKey]['data'];
        }
        
        $this->enforceRateLimit();
        $result = parent::getIPO($identifier);
        
        $this->cache[$cacheKey] = [
            'data' => $result,
            'time' => time()
        ];
        
        return $result;
    }
    
    public function clearCache() {
        $this->cache = [];
    }
    
    public function getCacheStats() {
        return [
            'cacheSize' => count($this->cache),
            'requestCount' => $this->requestCount
        ];
    }
}

// Usage
$client = new AdvancedIPOAlertsClient('YOUR_API_KEY');

try {
    // First request - will be cached
    $ipos1 = $client->getIPOs(['status' => 'upcoming']);
    
    // Second request - will return cached data
    $ipos2 = $client->getIPOs(['status' => 'upcoming']);
    
    echo "Cache stats: " . json_encode($client->getCacheStats()) . "\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Laravel Integration

<?php

// app/Services/IPOAlertsService.php
namespace App\Services;

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

class IPOAlertsService {
    private $apiKey;
    private $baseUrl = 'https://api.ipoalerts.in';
    
    public function __construct() {
        $this->apiKey = config('services.ipoalerts.api_key');
    }
    
    public function getIPOs($filters = []) {
        $cacheKey = 'ipoalerts_ipos_' . md5(serialize($filters));
        
        return Cache::remember($cacheKey, 300, function () use ($filters) {
            $response = Http::withHeaders([
                'x-api-key' => $this->apiKey,
                'Content-Type' => 'application/json'
            ])->get($this->baseUrl . '/ipos', $filters);
            
            if ($response->failed()) {
                throw new \Exception('API request failed: ' . $response->status());
            }
            
            return $response->json();
        });
    }
    
    public function getIPO($identifier) {
        $cacheKey = 'ipoalerts_ipo_' . $identifier;
        
        return Cache::remember($cacheKey, 300, function () use ($identifier) {
            $response = Http::withHeaders([
                'x-api-key' => $this->apiKey,
                'Content-Type' => 'application/json'
            ])->get($this->baseUrl . '/ipos/' . $identifier);
            
            if ($response->failed()) {
                throw new \Exception('API request failed: ' . $response->status());
            }
            
            return $response->json();
        });
    }
}

// config/services.php
return [
    'ipoalerts' => [
        'api_key' => env('IPOALERTS_API_KEY'),
    ],
];

// .env
IPOALERTS_API_KEY=your_api_key_here

// app/Http/Controllers/IPOController.php
namespace App\Http\Controllers;

use App\Services\IPOAlertsService;
use Illuminate\Http\Request;

class IPOController extends Controller {
    private $ipoAlertsService;
    
    public function __construct(IPOAlertsService $ipoAlertsService) {
        $this->ipoAlertsService = $ipoAlertsService;
    }
    
    public function index(Request $request) {
        try {
            $filters = $request->only(['status', 'type', 'page', 'limit']);
            $ipos = $this->ipoAlertsService->getIPOs($filters);
            
            return response()->json($ipos);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
    
    public function show($identifier) {
        try {
            $ipo = $this->ipoAlertsService->getIPO($identifier);
            return response()->json($ipo);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
?>