TTF Gas Price API in PHP

TTF Gas Price API in PHP

You need the latest TTF Gas spot price inside a PHP application without guessing units, symbols, or response fields. By the end of this guide you will query the Energy API for TTF Gas, parse the response in PHP, handle base currency nuances, and ship production-ready code that caches, validates, and displays EUR/MWh pricing correctly for finance workflows.

Scope and data you will use

This tutorial is narrowly focused on the TTF Gas instrument and the single endpoint you need to fetch it. Keep this handy reference in mind while you implement:

Illustration: TTF Gas Price API in PHP
  • Symbol name: TTF Gas
  • Symbol code: TTF_GAS
  • Unit: EUR/MWh
  • 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=TTF_GAS" --data-urlencode "api_key=YOUR_API_KEY"
  • Read rates.TTF_GAS, dates.TTF_GAS, currencies.TTF_GAS. base may be MIXED.

You will call a single HTTP GET endpoint and read three specific fields for the TTF_GAS symbol: the price in rates, the quote date in dates, and the currency used for that quote in currencies.

Endpoint and authentication

The Energy API exposes a latest endpoint where you request the instrument by symbol code and provide your API key as a query parameter. Do not add a base parameter when requesting TTF_GAS. Use this exact, copy-pasteable cURL for your first successful test:

curl -G "https://energy-api.com/api/v1/latest" --data-urlencode "symbols=TTF_GAS" --data-urlencode "api_key=YOUR_API_KEY"

Authentication is handled via the api_key query parameter. Replace YOUR_API_KEY with your key from the dashboard after you sign up. If you do not have a key yet, create one via Register. For endpoint reference, consult the Documentation.

Understand the response: fields you will actually use

The API returns a compact JSON payload. You must parse three places for the TTF_GAS symbol:

  • rates.TTF_GAS → the latest price
  • dates.TTF_GAS → the date for that price
  • currencies.TTF_GAS → the currency of the price (the unit remains EUR/MWh for the commodity; the currency denotes quote currency)

Here is a real response you can use to validate your parser:

{"success":true,"date":"2026-07-01","base":"USD","rates":{"TTF_GAS":17.93},"dates":{"TTF_GAS":"2026-07-01"},"currencies":{"TTF_GAS":"USD"},"base_filter_note":null}

Notes for implementation:

  • date is the server-wide valuation date; always read the per-symbol date from dates.TTF_GAS to display the TTF price date.
  • base is a top-level indicator and can be MIXED. Always read the per-symbol currency from currencies.TTF_GAS.
  • Do not pass base=USD in your request for TTF_GAS. If the API returns USD at currencies.TTF_GAS, use that value as-is.

The following official sample (different symbol shown) confirms the payload structure you will parse. It must be copied verbatim for your tests:

{
"success": true,
"date": "2026-10-03",
"base": "EUR",
"rates": {
"OMIE_ES_DA": 166.6015
},
"dates": {
"OMIE_ES_DA": "2026-10-03"
},
"currencies": {
"OMIE_ES_DA": "EUR"
},
"base_filter_note": null
}

Even though the instrument in this official payload is different, the structure is identical to TTF_GAS queries: success, date, base, and the symbol-indexed maps for rates, dates, and currencies.

PHP: fetch and parse TTF Gas in one function

The PHP example below does the following:

  • Performs a GET request with query parameters (symbols and api_key).
  • Validates HTTP and JSON decoding.
  • Extracts rates.TTF_GAS, dates.TTF_GAS, and currencies.TTF_GAS.
  • Normalizes the output for display and downstream use.

Single-call helper with curl and timeouts

<?php
declare(strict_types=1);

function fetchTtfGas(array $opts = []): array {
$apiKey = $opts['api_key'] ?? 'YOUR_API_KEY';
$endpoint = 'https://energy-api.com/api/v1/latest';
$query = http_build_query([
'symbols' => 'TTF_GAS',
'api_key' => $apiKey,
]);

$url = $endpoint . '?' . $query;

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5, // seconds
CURLOPT_TIMEOUT => 10, // hard cap
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'User-Agent: ttf-gas-php/1.0',
],
]);

$body = curl_exec($ch);
$err = curl_error($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($body === false) {
throw new RuntimeException('HTTP request failed: ' . $err);
}
if ($code < 200 || $code >= 300) {
throw new RuntimeException('Unexpected status ' . $code . ' with body: ' . substr($body, 0, 500));
}

$json = json_decode($body, true);
if (!is_array($json)) {
throw new RuntimeException('Invalid JSON payload');
}
if (empty($json['success'])) {
throw new RuntimeException('API indicated failure');
}

// Pull the fields you actually need
$rate = $json['rates']['TTF_GAS'] ?? null;
$priceDate = $json['dates']['TTF_GAS'] ?? null;
$priceCcy = $json['currencies']['TTF_GAS'] ?? null;
$topBase = $json['base'] ?? null;

if (!is_numeric($rate) || !$priceDate || !$priceCcy) {
throw new RuntimeException('Missing TTF_GAS fields in response');
}

// Return a minimal, typed record for downstream use
return [
'symbol' => 'TTF_GAS',
'unit' => 'EUR/MWh', // commodity unit from catalog
'price' => (float)$rate,
'price_date' => $priceDate, // ISO date
'price_ccy' => $priceCcy, // e.g., EUR or USD
'top_base' => $topBase, // informational
'fetched_at' => gmdate('c'), // audit stamp
'source' => $endpoint,
];
}

try {
$ttf = fetchTtfGas();
// Minimal presentation
echo sprintf(
"%s %0.4f %s (%s, quoted in %s)\n",
$ttf['symbol'],
$ttf['price'],
$ttf['unit'],
$ttf['price_date'],
$ttf['price_ccy']
);
} catch (Throwable $e) {
// Production: log to your aggregator
http_response_code(503);
echo "Service unavailable: " . $e->getMessage();
}

This code keeps the contract minimal: it returns a small array with exactly what your finance workflow needs. It does not add a base parameter, and it reads the symbol-scoped fields that matter.

PHP: lightweight file_get_contents alternative

If you cannot use cURL, you can still make a robust call using stream contexts with timeouts. This keeps your deployment surface tiny while preserving correct parsing and field checks.

<?php
declare(strict_types=1);

function fetchTtfGasSimple(string $apiKey = 'YOUR_API_KEY'): array {
$endpoint = 'https://energy-api.com/api/v1/latest';
$qs = http_build_query([
'symbols' => 'TTF_GAS',
'api_key' => $apiKey,
]);
$url = $endpoint . '?' . $qs;

$ctx = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 10,
'header' => implode("\r\n", [
'Accept: application/json',
'Connection: close',
]),
],
]);

$body = @file_get_contents($url, false, $ctx);
if ($body === false) {
$error = error_get_last();
throw new RuntimeException('HTTP request failed: ' . ($error['message'] ?? 'unknown error'));
}

$json = json_decode($body, true);
if (!is_array($json) || empty($json['success'])) {
throw new RuntimeException('Invalid or unsuccessful API response');
}

$rate = $json['rates']['TTF_GAS'] ?? null;
$dt = $json['dates']['TTF_GAS'] ?? null;
$ccy = $json['currencies']['TTF_GAS'] ?? null;

if (!is_numeric($rate) || !$dt || !$ccy) {
throw new RuntimeException('Missing key fields for TTF_GAS');
}

return [
'symbol' => 'TTF_GAS',
'price' => (float)$rate,
'date' => $dt,
'currency' => $ccy,
'unit' => 'EUR/MWh',
];
}

Use either PHP approach consistently in your application. The key point is the exact fields you parse and the absence of any base parameter in your request.

JavaScript example (Node.js or browser)

The same endpoint can be called from JavaScript using fetch. This example reads only the symbol-scoped fields and leaves the top-level base as an informational value.

async function getTtfGas() {
const url = new URL('https://energy-api.com/api/v1/latest');
url.searchParams.set('symbols', 'TTF_GAS');
url.searchParams.set('api_key', 'YOUR_API_KEY');

const res = await fetch(url.toString(), {
method: 'GET',
headers: {
'Accept': 'application/json',
'User-Agent': 'ttf-gas-js/1.0'
}
});

if (!res.ok) {
throw new Error(`Unexpected status ${res.status}`);
}

const data = await res.json();
if (!data.success) {
throw new Error('API indicated failure');
}

const price = data.rates?.TTF_GAS;
const asOf = data.dates?.TTF_GAS;
const ccy = data.currencies?.TTF_GAS;

if (typeof price !== 'number' || !asOf || !ccy) {
throw new Error('Missing fields for TTF_GAS');
}

return {
symbol: 'TTF_GAS',
unit: 'EUR/MWh',
price,
asOf,
currency: ccy,
base: data.base ?? null
};
}

getTtfGas()
.then(console.log)
.catch(err => console.error('Fetch error:', err));

This code is intentionally close to the PHP examples to make it obvious which fields drive your pricing UI or P&L logic.

Sample JSON responses you can test against

Use the following complete examples to validate your JSON parsing, contract tests, and caching logic. Copy them as-is.

Example A: Real TTF_GAS response

{"success":true,"date":"2026-07-01","base":"USD","rates":{"TTF_GAS":17.93},"dates":{"TTF_GAS":"2026-07-01"},"currencies":{"TTF_GAS":"USD"},"base_filter_note":null}

Interpretation: rates.TTF_GAS is 17.93 quoted in USD for the date in dates.TTF_GAS (2026-07-01). The commodity unit for TTF Gas is EUR/MWh. If you display currency alongside the value, show USD from currencies.TTF_GAS.

Example B: Official structure sample (different symbol)

{
"success": true,
"date": "2026-10-03",
"base": "EUR",
"rates": {
"OMIE_ES_DA": 166.6015
},
"dates": {
"OMIE_ES_DA": "2026-10-03"
},
"currencies": {
"OMIE_ES_DA": "EUR"
},
"base_filter_note": null
}

Interpretation: The per-symbol maps are the source of truth for price, date, and currency. Your TTF_GAS code should read the same locations, replacing OMIE_ES_DA with TTF_GAS.

Example C: Repeat of the real TTF_GAS payload for contract tests

{"success":true,"date":"2026-07-01","base":"USD","rates":{"TTF_GAS":17.93},"dates":{"TTF_GAS":"2026-07-01"},"currencies":{"TTF_GAS":"USD"},"base_filter_note":null}

Use this duplicate block to set up a second fixture in your test suite (e.g., one for parsing, one for cache hydration). Keeping fixtures identical ensures you isolate transport vs. parsing behavior.

Implementation details that save time in production

  • Units vs. currency: TTF Gas is quoted in EUR/MWh as a commodity unit. The currencies.TTF_GAS field tells you the currency used in that API response (e.g., EUR or USD). Never hardcode the display currency; always read currencies.TTF_GAS.
  • Base may be MIXED: The top-level base can be EUR, USD, or MIXED. Do not derive instrument currency from base; always use currencies.TTF_GAS.
  • No base parameter for TTF_GAS: Do not pass base=USD (or any base) when requesting TTF_GAS or EUA_CO2. The API will return the correct currency per symbol.
  • Timestamps and timezone: dates.* fields are ISO dates (no time). For audit logs, add your own fetched_at as an ISO 8601 UTC timestamp.
  • Caching: For dashboards and reports, cache results for a short TTL (e.g., 60–300 seconds) to reduce latency and protect your call budget. Include the symbol, per-symbol date, and currency in the cache key.
  • Error handling: Guard against transport errors, non-2xx statuses, and invalid JSON. Surface a 503 from your service if the upstream call fails and serve a last-known-good cached value when possible.
  • Non-trading days: Commodities can have days with limited or no updates. Your code should tolerate the same date returning across multiple fetches; avoid assuming daily increments.
  • Pagination: The latest endpoint returns a single snapshot, so there is no pagination to implement for TTF_GAS in this guide.

Data validation checklist for finance integrations

  • Always assert data.success === true.
  • Assert typeof rates.TTF_GAS is number and is finite.
  • Assert dates.TTF_GAS is a non-empty ISO date string.
  • Assert currencies.TTF_GAS is a 3-letter code and matches your downstream currency logic.
  • Log and store fetched_at (UTC) and the raw body for traceability.
  • Do not coerce or convert prices based on the top-level base; prefer the symbol’s currency field.

End-to-end test with cURL

Run this call locally and confirm your PHP and JavaScript parsers handle the output. Use the exact official command:

curl -G "https://energy-api.com/api/v1/latest" --data-urlencode "symbols=TTF_GAS" --data-urlencode "api_key=YOUR_API_KEY"

If your terminal output resembles Example A or shows the same field structure as Example B, your integration is correct. Remember to replace YOUR_API_KEY with your real key from the dashboard.

Plan, pricing, and call budgeting

According to the catalog facts: Starter $19.99/mo, trial 7 days / 50 calls. Align your cache TTL and refresh frequency with that allocation during trial. For details beyond this scope, see the Documentation.

FAQ

Q1: Which fields should I use to display “TTF Gas price on YYYY-MM-DD”?
Use rates.TTF_GAS for the price and dates.TTF_GAS for the date. Append the unit EUR/MWh and the currency from currencies.TTF_GAS in your label or tooltip.

Q2: Do I need to set a base currency in the request?
No. Do not pass base=USD (or any base) when requesting TTF_GAS. Always read currencies.TTF_GAS from the response.

Q3: How do I handle days without updates?
Design your cache to be tolerant of unchanged dates.TTF_GAS across multiple fetches. Keep your last-known-good value and surface the per-symbol date so users see when the price was last updated.

Q4: Can I query multiple symbols at once?
Yes, the endpoint accepts a symbols parameter, but this guide focuses on TTF_GAS only. If you add symbols, continue reading per-symbol fields (rates.*, dates.*, currencies.*) and avoid base filtering for TTF_GAS.

Q5: What should I log for auditability?
Log the URL, HTTP status, a truncated copy of the body, your fetched_at (UTC), and the parsed triple (rate, date, currency). This is sufficient to trace pricing used in finance reports.

Ready to integrate TTF Gas pricing into your PHP stack with a proper trial and a predictable starter plan? Create your key and start testing in minutes via Register.

Ready to get started?

Get your API key and start querying energy commodity prices in minutes.

Get API Key

Related posts