WTI Crude Price API in PHP
You need to pull the latest WTI Crude benchmark into a PHP application, parse the number safely, and present it in USD per barrel without second-guessing timezones or response shapes. By the end of this guide you will call the Energy API endpoint for WTI Crude, handle auth, parse the finance-ready fields, add retries and caching in PHP, and ship a clean price feed to your users.
What the endpoint returns and how pricing is represented
The Energy API exposes a single latest-prices endpoint you will call from PHP:
- HTTP method: GET
- Path: /api/v1/latest
- Query parameters:
symbols=(comma-separated),api_key= - Authentication: via
api_keyquery parameter (use YOUR_API_KEY) - Response fields of interest:
rates.<SYMBOL>,dates.<SYMBOL>,currencies.<SYMBOL>, and top-levelbase - Units: WTI Crude is in USD per barrel
Important finance notes:
- Read
rates.WTI_CRUDEas a decimal price (USD/barrel). - Read
dates.WTI_CRUDEfor the valuation date the rate applies to. - Read
currencies.WTI_CRUDEfor the instrument’s currency code (USD for WTI Crude). basecan be a currency like USD or the literal string MIXED when multiple symbols are not in the same currency. Always key offcurrencies.<SYMBOL>for per-symbol currency.
Origin catalog facts for WTI Crude
- Symbol name: WTI Crude
- Symbol code: WTI_CRUDE
- Unit: USD/barrel
- Auth: api_key query parameter. Placeholder YOUR_API_KEY only.
- Do not pass base=USD when you also need TTF_GAS or EUA_CO2.
- No MCP host. Starter $19.99/mo, trial 7 days / 50 calls.
- curl: curl -G "https://energy-api.com/api/v1/latest" --data-urlencode "symbols=WTI_CRUDE" --data-urlencode "api_key=YOUR_API_KEY"
- Read rates.WTI_CRUDE, dates.WTI_CRUDE, currencies.WTI_CRUDE. base may be MIXED.
For complete parameter and schema references, see the Documentation.
Quick sanity check with curl
Run this from your terminal to verify you can reach the Finance endpoint and receive WTI Crude data:
curl -G "https://energy-api.com/api/v1/latest" \
--data-urlencode "symbols=WTI_CRUDE" \
--data-urlencode "api_key=YOUR_API_KEY"
Real response example you should model against when parsing (values provided by the Energy API):
{"success":true,"date":"2026-09-22","base":"USD","rates":{"WTI_CRUDE":96.41},"dates":{"WTI_CRUDE":"2026-09-22"},"currencies":{"WTI_CRUDE":"USD"},"base_filter_note":null}
Field usage in your finance code:
rates.WTI_CRUDE: 96.41 (USD per barrel)dates.WTI_CRUDE: 2026-09-22 (valuation date)currencies.WTI_CRUDE: USD (currency of the rate)base: USD for this single-symbol call (could be MIXED on multi-instrument requests)
PHP: minimal client to fetch WTI Crude
This snippet uses PHP’s cURL extension. It builds the query string correctly, handles a network timeout, decodes JSON, and extracts the finance-ready fields you’ll store or render.
<?php
$endpoint = 'https://energy-api.com/api/v1/latest';
$params = [
'symbols' => 'WTI_CRUDE',
'api_key' => 'YOUR_API_KEY',
];
// Build URL with encoded query params
$url = $endpoint . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$raw = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno !== 0) {
// Network-level error: log and fail fast or use cache (see later section)
throw new RuntimeException('cURL error: ' . $err);
}
if ($http < 200 || $http >= 300) {
throw new RuntimeException('HTTP error ' . $http . ' body=' . $raw);
}
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
// Validate expected structure for WTI_CRUDE
if (
empty($data['success']) ||
!isset($data['rates']['WTI_CRUDE']) ||
!isset($data['dates']['WTI_CRUDE']) ||
!isset($data['currencies']['WTI_CRUDE'])
) {
throw new RuntimeException('Unexpected API response structure');
}
$wtiPrice = (float)$data['rates']['WTI_CRUDE']; // 96.41
$wtiDate = (string)$data['dates']['WTI_CRUDE']; // 2026-09-22
$wtiCcy = (string)$data['currencies']['WTI_CRUDE']; // USD
printf("WTI Crude: %.2f %s/barrel (as of %s)\n", $wtiPrice, $wtiCcy, $wtiDate);
Notes:
- Always parse
rates.WTI_CRUDEas a float in PHP to avoid string concatenation bugs in templating layers. - Rely on
dates.WTI_CRUDEfor the valuation date shown to users and stored in your finance database. - For multi-symbol calls, treat
baseas advisory; currency per symbol is authoritative viacurrencies.<SYMBOL>.
PHP: resilient client with retries and file cache
This version adds exponential backoff retries and a simple on-disk cache to keep your finance UI responsive if the network blips. Tune TTLs and retry counts to your latency budget.
<?php
function fetchLatestWTI(string $apiKey, int $retries = 2, int $timeout = 8): array {
$endpoint = 'https://energy-api.com/api/v1/latest';
$params = [
'symbols' => 'WTI_CRUDE',
'api_key' => $apiKey,
];
$url = $endpoint . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
$attempt = 0;
$backoff = 0.5; // seconds
while (true) {
$attempt++;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$raw = curl_exec($ch);
$errno = curl_errno($ch);
$err = curl_error($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno === 0 && $http >= 200 && $http < 300) {
$data = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('JSON parse error: ' . json_last_error_msg());
}
return $data;
}
if ($attempt > $retries) {
$details = $errno ? ('cURL error: ' . $err) : ('HTTP ' . $http . ' body=' . $raw);
throw new RuntimeException('Energy API request failed after retries: ' . $details);
}
usleep((int)($backoff * 1e6));
$backoff *= 2;
}
}
function cachePath(): string {
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'energy_cache';
if (!is_dir($dir)) {
mkdir($dir, 0775, true);
}
return $dir . DIRECTORY_SEPARATOR . 'wti_crude_latest.json';
}
function getWTIWithCache(string $apiKey, int $ttlSeconds = 300): array {
$cacheFile = cachePath();
// Serve fresh-enough cache
if (is_file($cacheFile)) {
$age = time() - filemtime($cacheFile);
if ($age < $ttlSeconds) {
$cached = file_get_contents($cacheFile);
$data = json_decode($cached, true);
if (is_array($data)) {
return $data;
}
}
}
// Refresh from API
$data = fetchLatestWTI($apiKey);
// Validate minimal structure before caching
if (!empty($data['success']) && isset($data['rates']['WTI_CRUDE'])) {
file_put_contents($cacheFile, json_encode($data));
}
return $data;
}
// Usage
try {
$data = getWTIWithCache('YOUR_API_KEY', 180); // 3-minute TTL
$price = (float)$data['rates']['WTI_CRUDE'];
$asOf = (string)$data['dates']['WTI_CRUDE'];
$ccy = (string)$data['currencies']['WTI_CRUDE'];
echo sprintf("WTI %.2f %s/bbl (as of %s)\n", $price, $ccy, $asOf);
} catch (Throwable $e) {
// Fallback: last-known-good cache or safe default display
error_log($e->getMessage());
echo "WTI price temporarily unavailable\n";
}
Why these defaults:
- TTL of 3–5 minutes is typically acceptable for finance dashboards showing benchmark commodities, while minimizing request volume.
- Use retries with small exponential backoff to smooth transient errors without blocking page loads for too long.
Finance-specific parsing details and unit sanity checks
Ensure your downstream code treats WTI Crude as a price in USD per barrel. Display labels explicitly so units are never ambiguous in a finance UI or export.
- Unit: “USD/barrel” for WTI Crude. When presenting, formats like “96.41 USD/bbl” reduce ambiguity.
- Currency: read from
currencies.WTI_CRUDE, not frombase, so multi-symbol calls do not confuse your P&L or risk reports. - Date:
dates.WTI_CRUDEis a calendar date (no timezone offset required). Treat it as the valuation date for EOD alignment in finance systems. - Non-trading days: energy benchmarks may publish an unchanged rate on weekends/holidays. Do not assume daily variation; always read the provided date.
Real JSON examples you can diff against
Example A — Latest WTI Crude (use these exact values in your tests):
{"success":true,"date":"2026-09-22","base":"USD","rates":{"WTI_CRUDE":96.41},"dates":{"WTI_CRUDE":"2026-09-22"},"currencies":{"WTI_CRUDE":"USD"},"base_filter_note":null}
Example B — Another symbol to illustrate base/currency behavior (provided response values):
{"success":true,"date":"2026-09-29","base":"EUR","rates":{"OMIE_ES_DA":130.0965},"dates":{"OMIE_ES_DA":"2026-09-29"},"currencies":{"OMIE_ES_DA":"EUR"},"base_filter_note":null}
Example C — Repeatable WTI baseline for parser validation (identical to Example A to verify idempotent parsing in tests):
{"success":true,"date":"2026-09-22","base":"USD","rates":{"WTI_CRUDE":96.41},"dates":{"WTI_CRUDE":"2026-09-22"},"currencies":{"WTI_CRUDE":"USD"},"base_filter_note":null}
In production, always read rates via their symbol keys and do not rely on positional assumptions when decoding JSON.
JavaScript example (Node.js or browser) for parity checks
Use this alongside PHP to compare parsing and ensure consistent finance outputs across services.
async function fetchWTI() {
const params = new URLSearchParams({
symbols: 'WTI_CRUDE',
api_key: 'YOUR_API_KEY'
});
const url = 'https://energy-api.com/api/v1/latest?' + params.toString();
const res = await fetch(url, { headers: { 'Accept': 'application/json' }, cache: 'no-store' });
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
if (!data.success || !data.rates || data.rates.WTI_CRUDE == null) {
throw new Error('Unexpected schema');
}
const price = Number(data.rates.WTI_CRUDE);
const asOf = String(data.dates.WTI_CRUDE);
const ccy = String(data.currencies.WTI_CRUDE);
console.log(`WTI ${price.toFixed(2)} ${ccy}/bbl (as of ${asOf})`);
}
fetchWTI().catch(err => {
console.error('Failed to fetch WTI:', err);
});
Composing multi-instrument requests without breaking currency assumptions
If you expand beyond WTI in the same request, you may receive a base value of MIXED or a base that reflects a different currency. Always:
- Read each symbol’s currency via
currencies.<SYMBOL>. - Do not append
base=USDwhen requesting symbols that include TTF_GAS or EUA_CO2. - Normalize in your finance layer only after parsing per-symbol currencies (e.g., convert to a reporting currency using your FX module).
For WTI-only calls, the base is USD and the symbol’s currency is USD, which makes direct display straightforward.
Caching, refresh cadence, and deployment notes
- Refresh cadence: a 1–5 minute polling interval balances timeliness with request volume for finance dashboards.
- Server-side caching: store the full JSON response and the UTC fetch timestamp. Serve cached data during outages.
- Client-side: send max-age headers conservative enough to avoid stale finance displays; or disable caching and rely on your PHP cache.
- Time boundaries: use
dates.WTI_CRUDEas the valuation date for reporting. Avoid assuming midnight UTC turnover; always trust the response’s date. - Error budgets: wrap your calls with retries and circuit breakers to avoid cascading failures under brief network instability.
Pricing, access, and where to onboard
You authenticate with an api_key query parameter. A starter plan is available at $19.99 per month with a 7-day trial including 50 calls. To provision an API key and review available symbols and fields, use the links below.
FAQ
How do I get just WTI Crude without other symbols?
Call GET /api/v1/latest with symbols=WTI_CRUDE and your api_key. Parse rates.WTI_CRUDE, dates.WTI_CRUDE, and currencies.WTI_CRUDE.
What timezone should I assume for the date?
Use the provided dates.WTI_CRUDE value as a calendar date for valuation. Do not add timezone math; store and display it as the as-of date for finance reporting.
Will the base always be USD?
Not necessarily. The top-level base can be MIXED or a different currency in multi-symbol calls. For WTI-only calls it is USD. Always trust currencies.WTI_CRUDE for the symbol’s currency.
Can I include TTF_GAS or EUA_CO2 together with WTI_CRUDE?
Yes, but do not add base=USD when requesting TTF_GAS or EUA_CO2. Parse currencies per symbol and normalize in your finance layer if needed.
How should I handle outages?
Implement short retries with backoff and keep a short-lived server-side cache. If the live call fails, serve the cached JSON and clearly label the as-of date from dates.WTI_CRUDE.
Ready to integrate WTI Crude into your PHP app? Create your key and start with the latest endpoint in minutes: Register. For endpoint details and field reference, see the Documentation.
Ready to get started?
Get your API key and start querying energy commodity prices in minutes.
Get API KeyRelated posts
A WTI crude price API returns WTI_CRUDE as JSON. Energy-API GET /api/v1/latest?symbols=WTI_CRUDE. Official mix...
Read more →
Discover how to seamlessly integrate the latest Brent crude price into your finance workflows using a Finance...
Read more →
An energy price API returns BRENT_CRUDE and TTF_GAS as JSON. Energy-API GET /api/v1/latest uses api_key. Start...
Read more →
Discover how to build interactive dashboards using the Energy API to visualize energy data, streamline trading...
Read more →
Unlock the potential of algorithmic trading with a Finance API. Discover how energy traders can streamline dat...
Read more →