Oil Price API Documentation - Quick Start in 5 Minutes | REST API
GitHub
GitHub

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.

Requirements

  • PHP 7.4 or higher
  • cURL extension enabled
  • JSON extension enabled

Installation

Using Composer (recommended):

composer require guzzlehttp/guzzle

Or use PHP's built-in cURL for zero dependencies.

Quick Start

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']['WTI_USD']['formatted'];

Complete API Client Class

<?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
$commodities = ['WTI_USD', 'BRENT_CRUDE_USD', 'NATURAL_GAS_USD'];
$prices = $client->getLatestPrices($commodities);

foreach ($prices['data'] as $code => $data) {
    echo "{$code}: {$data['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'][$atts['code']])) {
        return $prices['data'][$atts['code']]['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

Next Steps

  • Authentication Guide - API key management
  • API Reference - Complete endpoint documentation
  • Historical Data - Time-series queries
  • Rate Limiting - Usage limits and best practices
Last Updated: 12/28/25, 12:24 AM