OilPriceAPI Docs
GitHub
GitHub
  • SDKs & Languages

    • SDKs & Language Guides
    • SDK Examples for Pagination and Error Handling
    • TypeScript Response Types
  • Language Guides

    • Java Oil Price API Integration
    • Go Oil Price API Integration
    • Rust Oil Price API Integration
    • PHP Oil Price API Integration
    • Ruby Oil Price API Integration
    • C# .NET Oil Price API Integration
    • R Language Oil Price API Integration

PHP Integration Guide

Integrate OilPriceAPI into your PHP applications to access real-time oil prices, crude oil market data, and commodity pricing for energy sector applications. Build solutions for gas station websites, fleet management portals, and logistics platforms.

Requirements

  • Official SDK: PHP 8.1 or higher, with the curl and json extensions (bundled with virtually every PHP install)
  • Manual integration: PHP 7.4 or higher, cURL extension, JSON extension

Installation

Install the official PHP SDK with Composer:

composer require oilpriceapi/oilpriceapi

The SDK has zero dependencies (no Guzzle, no framework), so it drops into shared hosting, WordPress themes/plugins, and any existing project without conflicting with your host's packages.

  • Packagist: oilpriceapi/oilpriceapi
  • GitHub: OilpriceAPI/oilpriceapi-php

Manual / no-SDK fallback

If you cannot use Composer, or you prefer to own the HTTP layer, you can call the API with PHP's built-in cURL (see Using cURL below) or with an HTTP client you already have, such as Guzzle:

composer require guzzlehttp/guzzle

SDK Quick Start

<?php

require 'vendor/autoload.php';

use OilPriceAPI\Client;

$client = new Client('your_api_key'); // or set the OILPRICEAPI_KEY env var

$brent = $client->latest('BRENT_CRUDE_USD');
echo $brent->price;    // float, e.g. USD per barrel
echo $brent->currency; // "USD"
echo $brent->updatedAt?->format('Y-m-d H:i');

Calling latest() without a code returns every commodity on your plan as a list of Price objects.

Historical prices

$day   = $client->pastDay('BRENT_CRUDE_USD');   // last 24 hours
$week  = $client->pastWeek('BRENT_CRUDE_USD');
$month = $client->pastMonth('BRENT_CRUDE_USD');
$year  = $client->pastYear('BRENT_CRUDE_USD');

foreach ($week as $price) {
    echo $price->updatedAt?->format('Y-m-d H:i'), ' -> ', $price->price, PHP_EOL;
}

Each method returns a list<OilPriceAPI\Price>. Price is an immutable DTO with code, price (float), currency, updatedAt (DateTimeImmutable|null), change24h (float|null), plus name, unit, type and formatted where the API provides them, and a toArray() helper.

Try it without an API key (demo mode)

$client = new \OilPriceAPI\Client(); // no key

foreach ($client->demoPrices() as $price) {
    printf("%s: %s %.2f\n", $price->code, $price->currency, $price->price);
}

Demo mode is rate limited per IP and covers free-tier commodities only.

Any endpoint: the raw() escape hatch

New endpoints ship in the API before they ship in the SDK. raw() returns the full decoded JSON envelope for any path:

$response = $client->raw()->get('/v1/futures/ice-brent/curve', ['unit' => 'usd']);
// ['status' => 'success', 'data' => [...]]

Error handling

use OilPriceAPI\Exception\ApiException;
use OilPriceAPI\Exception\AuthenticationException;
use OilPriceAPI\Exception\RateLimitException;

try {
    $price = $client->latest('BRENT_CRUDE_USD');
} catch (AuthenticationException $e) {
    // 401 or missing key
} catch (RateLimitException $e) {
    // 429 after retries - $e->retryAfter (seconds), $e->limit
} catch (ApiException $e) {
    // everything else - $e->statusCode, $e->responseBody
}

All exceptions extend ApiException, so a single catch handles everything.

Retries & timeouts

Requests that hit 429 or 5xx are retried automatically (default: 3 retries) with exponential backoff plus jitter, honoring Retry-After when the API sends it. Both are configurable:

$client = new \OilPriceAPI\Client(
    apiKey: 'your_api_key',
    timeout: 10.0,     // seconds per request (default 10)
    maxRetries: 3,     // retries on 429/5xx (default 3)
);

Manual Integration (No SDK)

The rest of this guide shows how to call the API directly, without the SDK. Use it if you cannot install Composer packages, or you want to see exactly what the SDK does under the hood.

Using cURL (No Dependencies)

<?php

$apiKey = getenv('OILPRICE_API_KEY');

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => 'https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Token ' . $apiKey,
        'Content-Type: application/json'
    ]
]);

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

if ($httpCode === 200) {
    $data = json_decode($response, true);
    print_r($data);
}

Using Guzzle

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://api.oilpriceapi.com/v1/',
    'headers' => [
        'Authorization' => 'Token ' . getenv('OILPRICE_API_KEY')
    ]
]);

$response = $client->get('prices/latest', [
    'query' => ['by_code' => 'WTI_USD']
]);

$data = json_decode($response->getBody(), true);
echo "WTI Price: " . $data['data']['formatted'];

Hand-Rolled API Client Class (No SDK)

If you cannot add the official SDK to your project, this class is a self-contained equivalent you can copy in. Prefer composer require oilpriceapi/oilpriceapi when you can — it ships retries, typed exceptions and typed DTOs.

<?php

class OilPriceAPI
{
    private string $apiKey;
    private string $baseUrl = 'https://api.oilpriceapi.com/v1';
    private int $timeout = 30;

    public function __construct(?string $apiKey = null)
    {
        $this->apiKey = $apiKey ?? getenv('OILPRICE_API_KEY');

        if (empty($this->apiKey)) {
            throw new InvalidArgumentException('API key is required');
        }
    }

    private function request(string $endpoint, array $params = []): array
    {
        $url = $this->baseUrl . $endpoint;

        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_HTTPHEADER => [
                'Authorization: Token ' . $this->apiKey,
                'Content-Type: application/json',
                'Accept: application/json'
            ]
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new RuntimeException("cURL error: $error");
        }

        return $this->handleResponse($response, $httpCode);
    }

    private function handleResponse(string $response, int $httpCode): array
    {
        $data = json_decode($response, true);

        switch ($httpCode) {
            case 200:
                return $data;
            case 401:
                throw new RuntimeException('Invalid API key');
            case 403:
                throw new RuntimeException('Access forbidden');
            case 429:
                throw new RuntimeException('Rate limit exceeded');
            default:
                throw new RuntimeException("API error: HTTP $httpCode");
        }
    }

    public function getLatestPrices(string|array $codes): array
    {
        if (is_array($codes)) {
            $codes = implode(',', $codes);
        }

        return $this->request('/prices/latest', ['by_code' => $codes]);
    }

    public function getHistoricalPrices(string $code, int $days = 7): array
    {
        $endpoint = "/prices/past_{$days}_days";
        return $this->request($endpoint, ['by_code' => $code]);
    }

    public function getCommodities(): array
    {
        return $this->request('/commodities');
    }
}

Usage Examples

Fetch Multiple Commodities

<?php

require_once 'OilPriceAPI.php';

$client = new OilPriceAPI();

// Get multiple oil prices at once (a comma-separated request returns a `prices` array)
$commodities = ['WTI_USD', 'BRENT_CRUDE_USD', 'NATURAL_GAS_USD'];
$prices = $client->getLatestPrices($commodities);

foreach ($prices['data']['prices'] as $price) {
    echo "{$price['code']}: {$price['formatted']}\n";
}

Historical Price Analysis

<?php

$client = new OilPriceAPI();

// Get past week of WTI prices
$history = $client->getHistoricalPrices('WTI_USD', 7);

echo "WTI Price History:\n";
foreach ($history['data'] as $point) {
    $date = date('Y-m-d', strtotime($point['created_at']));
    echo "  {$date}: \${$point['price']}\n";
}

// Calculate price change
$prices = array_column($history['data'], 'price');
$change = end($prices) - reset($prices);
$percentChange = ($change / reset($prices)) * 100;

echo sprintf("\nWeekly Change: %+.2f (%.2f%%)\n", $change, $percentChange);

Laravel Integration

<?php

namespace App\Services;

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

class OilPriceService
{
    private string $apiKey;
    private string $baseUrl = 'https://api.oilpriceapi.com/v1';

    public function __construct()
    {
        $this->apiKey = config('services.oilpriceapi.key');
    }

    public function getLatestPrices(array $codes): array
    {
        $cacheKey = 'oil_prices_' . implode('_', $codes);

        return Cache::remember($cacheKey, 300, function () use ($codes) {
            $response = Http::withHeaders([
                'Authorization' => 'Token ' . $this->apiKey
            ])->get($this->baseUrl . '/prices/latest', [
                'by_code' => implode(',', $codes)
            ]);

            if ($response->failed()) {
                throw new \RuntimeException('OilPriceAPI request failed');
            }

            return $response->json();
        });
    }
}

// Usage in Controller
class PriceController extends Controller
{
    public function index(OilPriceService $oilService)
    {
        $prices = $oilService->getLatestPrices(['WTI_USD', 'BRENT_CRUDE_USD']);

        return view('prices.index', compact('prices'));
    }
}

WordPress Integration

<?php

function get_oil_prices($codes = ['WTI_USD']) {
    $api_key = get_option('oilpriceapi_key');
    $cache_key = 'oil_prices_' . md5(implode(',', $codes));

    // Check transient cache
    $cached = get_transient($cache_key);
    if ($cached !== false) {
        return $cached;
    }

    $response = wp_remote_get(
        'https://api.oilpriceapi.com/v1/prices/latest?by_code=' . implode(',', $codes),
        [
            'headers' => ['Authorization' => 'Token ' . $api_key],
            'timeout' => 15
        ]
    );

    if (is_wp_error($response)) {
        return null;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    // Cache for 5 minutes
    set_transient($cache_key, $data, 300);

    return $data;
}

// Shortcode usage: [oil_price code="WTI_USD"]
add_shortcode('oil_price', function($atts) {
    $atts = shortcode_atts(['code' => 'WTI_USD'], $atts);
    $prices = get_oil_prices([$atts['code']]);

    if ($prices && isset($prices['data']['formatted'])) {
        return $prices['data']['formatted'];
    }

    return 'Price unavailable';
});

Error Handling

<?php

class OilPriceAPIException extends Exception {}
class RateLimitException extends OilPriceAPIException {}
class AuthenticationException extends OilPriceAPIException {}

function fetchWithRetry(OilPriceAPI $client, string $code, int $maxRetries = 3): array
{
    $lastException = null;

    for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
        try {
            return $client->getLatestPrices($code);
        } catch (RateLimitException $e) {
            $lastException = $e;
            $backoff = pow(2, $attempt);
            error_log("Rate limited, waiting {$backoff}s before retry");
            sleep($backoff);
        } catch (Exception $e) {
            throw $e; // Don't retry other errors
        }
    }

    throw $lastException;
}

Best Practices

Environment Variables

// .env file
OILPRICE_API_KEY=opa_live_your_key_here

// Load with vlucas/phpdotenv
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$apiKey = $_ENV['OILPRICE_API_KEY'];

Response Caching

function getCachedPrices(OilPriceAPI $client, array $codes, int $ttl = 300): array
{
    $cacheFile = sys_get_temp_dir() . '/oil_prices_' . md5(implode(',', $codes)) . '.json';

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $ttl) {
        return json_decode(file_get_contents($cacheFile), true);
    }

    $prices = $client->getLatestPrices($codes);
    file_put_contents($cacheFile, json_encode($prices));

    return $prices;
}

Common Commodity Codes

CodeDescription
WTI_USDWest Texas Intermediate Crude Oil
BRENT_CRUDE_USDBrent Crude Oil
NATURAL_GAS_USDNatural Gas (Henry Hub)
HEATING_OIL_USDHeating Oil No. 2
DIESEL_USDUltra Low Sulfur Diesel

Frequently Asked Questions

Is there an official SDK for PHP?

Yes. The official PHP SDK is v2.0.0, published on Packagist as oilpriceapi/oilpriceapi with source at OilpriceAPI/oilpriceapi-php.

composer require oilpriceapi/oilpriceapi

It requires PHP 8.1+, has zero dependencies (only ext-curl and ext-json), and works on shared hosting and inside WordPress. It ships automatic retries, typed exceptions and immutable Price DTOs. See the SDK Quick Start above. The cURL and Guzzle examples in this guide remain valid if you prefer to integrate manually.

How do I handle rate limiting in PHP?

Implement exponential backoff when you receive 429 (Too Many Requests) responses. Use sleep() with increasing delays between retries:

$backoff = pow(2, $attempt);
sleep($backoff);

What's the recommended error handling approach?

Always check HTTP status codes before parsing responses. Handle network timeouts and implement proper retry logic for transient failures. Use custom exception classes like RateLimitException and AuthenticationException for specific error handling.

Can I use async/concurrent requests?

PHP supports async requests through libraries like Guzzle's async features or ReactPHP. For most use cases, consider using Guzzle's Pool class or Promise interface to make concurrent requests when fetching multiple commodity prices.

Related Resources

  • Packagist Package - Official PHP SDK (composer require oilpriceapi/oilpriceapi)
  • GitHub Repository - PHP SDK source, examples, and issues
  • Google Sheets Integration - No-code spreadsheet alternative
  • Zapier Integration - Automate without coding
  • Make Integration - Visual workflow automation
  • Gas Station API - Retail fuel pricing solutions
  • Fleet Management API - Fleet cost tracking
  • Logistics Fuel API - Supply chain applications
  • Ruby Developer Guide - Alternative language guide
  • Python Developer Guide - Data science integration
  • Authentication Guide - API key management
  • API Reference - Complete endpoint documentation
  • Rate Limiting - Usage limits and best practices
Last Updated: 7/16/26, 3:41 PM
Prev
Rust Oil Price API Integration
Next
Ruby Oil Price API Integration