Spain Carbon Intensity Spot Price
You need to programmatically fetch the current Spain Carbon Intensity spot price and wire it into your app. By the end of this guide, you’ll have a copy-pasteable PHP client that calls the Energy API for the Spain Carbon Intensity symbol, parses the response safely, and handles real-world conditions like unavailable symbols, mixed bases, and caching.
What you’ll build and why it matters
We’ll build a small, production-ready PHP integration that queries the Energy API’s latest endpoint for Spain’s grid carbon intensity, reads the core fields you actually use in apps (rates, dates, currencies, base), and handles both success and failure envelopes. You’ll also see a compact Python example if PHP isn’t your primary language.
Origin catalog facts
- Symbol name: Spain Carbon Intensity
- Symbol code: CARBON_INT_ES
- Unit: gCO2/kWh
- 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=CARBON_INT_ES" --data-urlencode "api_key=YOUR_API_KEY"
- Read rates.CARBON_INT_ES, dates.CARBON_INT_ES, currencies.CARBON_INT_ES. base may be MIXED.
Endpoint, method, and authentication
The integration uses an HTTP GET against a single endpoint. Authentication is via an api_key query parameter; keep your key in server-side configuration and never embed it in public client code.
- Method: GET
- Endpoint: https://energy-api.com/api/v1/latest
- Query parameters:
- symbols=CARBON_INT_ES
- api_key=YOUR_API_KEY
Official sample: cURL and JSON
Copy this cURL exactly to test connectivity and auth:
curl -G "https://energy-api.com/api/v1/latest" --data-urlencode "symbols=CARBON_INT_ES" --data-urlencode "api_key=YOUR_API_KEY"
Official example JSON (field names and envelope format to rely on):
{
"success": true,
"date": "2026-11-16",
"base": "EUR",
"rates": {
"OMIE_ES_DA": 132.552
},
"dates": {
"OMIE_ES_DA": "2026-11-16"
},
"currencies": {
"OMIE_ES_DA": "EUR"
},
"base_filter_note": null,
"missing_symbols": null
}
How to read it:
- success: Boolean operation status for the call.
- date: The API’s reference date at the top level (not a per-symbol timestamp).
- base: The base unit or currency context. For carbon intensity, base may be MIXED.
- rates: A dictionary keyed by symbol. For our use, read rates.CARBON_INT_ES.
- dates: Per-symbol value date. Read dates.CARBON_INT_ES.
- currencies: Per-symbol currency or unit tag. Read currencies.CARBON_INT_ES.
- missing_symbols: If provided and non-null, a list of symbols that couldn’t be served.
Real API response (live call did not succeed)
When a symbol is temporarily unavailable, you’ll receive a structured error envelope. Here is the exact error observed for CARBON_INT_ES at the time of writing:
{"success":false,"error":"Symbol CARBON_INT_ES is not currently available. See \/api\/v1\/symbols for the current catalog."}
Production code should treat success=false as an operational error, log the message, and decide whether to retry, back off, or fall back to cached values.
PHP: end-to-end integration for Spain Carbon Intensity
The PHP client below does four things:
- Builds the query for symbols=CARBON_INT_ES with api_key.
- Performs a GET with a short timeout and sensible error handling.
- Parses JSON and validates the success flag.
- Extracts rates.CARBON_INT_ES, dates.CARBON_INT_ES, currencies.CARBON_INT_ES, and base.
<?php
declare(strict_types=1);
/**
* Fetch Spain Carbon Intensity (CARBON_INT_ES) from Energy API.
* Notes:
* - Authentication: api_key query parameter.
* - Units: gCO2/kWh.
* - base may be MIXED for non-currency series.
* - Handle success=false envelopes and null/missing fields.
*/
function fetchSpainCarbonIntensity(string $apiKey): array {
$endpoint = 'https://energy-api.com/api/v1/latest';
$query = http_build_query([
'symbols' => 'CARBON_INT_ES',
'api_key' => $apiKey,
]);
$url = $endpoint . '?' . $query;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 10, // Network timeout in seconds
CURLOPT_CONNECTTIMEOUT => 5, // Connection timeout in seconds
CURLOPT_HTTPGET => true,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
],
]);
$body = curl_exec($ch);
$errNo = curl_errno($ch);
$err = curl_error($ch);
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($errNo !== 0) {
throw new RuntimeException('HTTP transport error: ' . $err, $errNo);
}
if ($code < 200 || $code >= 300) {
throw new RuntimeException('Unexpected HTTP status: ' . $code . ' Body: ' . substr((string)$body, 0, 500));
}
$json = json_decode((string)$body, true);
if (!is_array($json)) {
throw new RuntimeException('Malformed JSON response');
}
// Handle error envelope
if (isset($json['success']) && $json['success'] === false) {
$msg = isset($json['error']) ? (string)$json['error'] : 'Unknown API error';
throw new RuntimeException('Energy API error: ' . $msg);
}
// Validate expected containers
$rates = $json['rates'] ?? [];
$dates = $json['dates'] ?? [];
$currencies = $json['currencies'] ?? [];
$base = $json['base'] ?? null;
if (!array_key_exists('CARBON_INT_ES', $rates)) {
// The symbol may be missing even if success=true; check missing_symbols for diagnostics
$missing = $json['missing_symbols'] ?? null;
$note = $missing ? (' Missing: ' . json_encode($missing)) : '';
throw new RuntimeException('CARBON_INT_ES not present in rates.' . $note);
}
// Extract scalar fields with defensive defaults
$value = $rates['CARBON_INT_ES']; // numeric, gCO2/kWh
$valueDate = $dates['CARBON_INT_ES'] ?? null; // ISO date string (if provided)
$unitOrCode = $currencies['CARBON_INT_ES'] ?? 'gCO2/kWh'; // unit tag
if (!is_numeric($value)) {
throw new RuntimeException('CARBON_INT_ES value is not numeric');
}
return [
'symbol' => 'CARBON_INT_ES',
'value' => (float)$value,
'unit' => $unitOrCode, // expected gCO2/kWh
'value_date' => $valueDate,
'base' => $base, // may be MIXED
'raw' => $json, // keep for auditing
];
}
// Example usage:
try {
$apiKey = 'YOUR_API_KEY'; // Store securely (env var, secrets manager)
$result = fetchSpainCarbonIntensity($apiKey);
// Application-side formatting or storage
printf(
"%s: %.2f %s (date=%s, base=%s)\n",
$result['symbol'],
$result['value'],
$result['unit'],
$result['value_date'] ?? 'n/a',
$result['base'] ?? 'n/a'
);
// Simple caching suggested: write $result to a key-value store with a short TTL
} catch (Throwable $e) {
// Log and optionally serve the last known cached value
error_log('Energy API fetch failed: ' . $e->getMessage());
// Fallback: load cache, or render an error state
}
Python quick start (same endpoint)
If you prefer Python for diagnostics or cron tasks, this is a compact version of the same logic:
import os
import json
import sys
import urllib.parse
import urllib.request
def fetch_spain_carbon_intensity(api_key: str) -> dict:
endpoint = "https://energy-api.com/api/v1/latest"
params = {
"symbols": "CARBON_INT_ES",
"api_key": api_key,
}
url = endpoint + "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=10) as resp:
status = resp.getcode()
if status < 200 or status >= 300:
raise RuntimeError(f"HTTP {status}: " + resp.read().decode("utf-8", errors="ignore"))
data = json.loads(resp.read().decode("utf-8"))
if data.get("success") is False:
raise RuntimeError(f"Energy API error: {data.get('error')}")
rates = data.get("rates", {})
dates = data.get("dates", {})
currencies = data.get("currencies", {})
base = data.get("base")
if "CARBON_INT_ES" not in rates:
raise RuntimeError(f"CARBON_INT_ES absent in rates. Missing: {data.get('missing_symbols')}")
return {
"symbol": "CARBON_INT_ES",
"value": float(rates["CARBON_INT_ES"]),
"unit": currencies.get("CARBON_INT_ES", "gCO2/kWh"),
"value_date": dates.get("CARBON_INT_ES"),
"base": base,
"raw": data,
}
if __name__ == "__main__":
api_key = os.getenv("ENERGY_API_KEY", "YOUR_API_KEY")
try:
res = fetch_spain_carbon_intensity(api_key)
print(f"{res['symbol']}: {res['value']} {res['unit']} (date={res['value_date']}, base={res['base']})")
except Exception as e:
print("Fetch failed:", e, file=sys.stderr)
sys.exit(1)
Additional JSON examples you can test locally
Use these to validate parsers and log formatting. They are structured with the same fields you’ll consume for CARBON_INT_ES.
1) Success response for Spain Carbon Intensity (EUR base)
{
"success": true,
"date": "2026-11-16",
"base": "EUR",
"rates": {
"CARBON_INT_ES": 165.42
},
"dates": {
"CARBON_INT_ES": "2026-11-16"
},
"currencies": {
"CARBON_INT_ES": "gCO2/kWh"
},
"base_filter_note": null,
"missing_symbols": null
}
2) Success response with mixed base (common for non-currency units)
{
"success": true,
"date": "2026-11-16",
"base": "MIXED",
"rates": {
"CARBON_INT_ES": 149.87
},
"dates": {
"CARBON_INT_ES": "2026-11-16"
},
"currencies": {
"CARBON_INT_ES": "gCO2/kWh"
},
"base_filter_note": null,
"missing_symbols": null
}
3) Success response but symbol filtered out (diagnostic: missing_symbols)
{
"success": true,
"date": "2026-11-16",
"base": "MIXED",
"rates": {
},
"dates": {
},
"currencies": {
},
"base_filter_note": null,
"missing_symbols": [ "CARBON_INT_ES" ]
}
4) Error envelope identical to a real failure mode
{"success":false,"error":"Symbol CARBON_INT_ES is not currently available. See \/api\/v1\/symbols for the current catalog."}
How to interpret values for carbon intensity
Spain Carbon Intensity is measured in grams of CO2 per kilowatt-hour (gCO2/kWh). Your application should:
- Treat the numeric value at rates.CARBON_INT_ES as a scalar in gCO2/kWh.
- Display the unit explicitly so users don’t mistake it for currency.
- Use dates.CARBON_INT_ES as the effective date associated with the value.
- Expect base to be MIXED for non-currency series.
Caching, TTLs, and retries
Do not assume continuous availability of CARBON_INT_ES. Implement a short-term cache (e.g., 1–5 minutes) to smooth over transient upstream issues and reduce repeated calls. If you receive success=false or a 5xx, back off and serve the last known cached value with a timestamp so users understand freshness.
Given that energy and grid metrics can update intra-day, avoid long-lived caches if your UX promises real-time values. Prefer a small cache with a circuit breaker to limit repeated failures.
Timezones, dates, and non-trading days
- dates.CARBON_INT_ES is an ISO date string. Store and compare as UTC-normalized strings or date objects.
- Some energy series may not change on weekends or holidays. Your cache should not assume constant churn; if the value repeats, treat it as valid.
- Top-level date can represent the API’s reference date; when in doubt for display, prefer the per-symbol field at dates.CARBON_INT_ES.
Error handling and diagnostics
- Always check success. If false, read error for a human-readable cause.
- Inspect missing_symbols when success=true but a symbol is absent in rates. This often explains partial results.
- Do not pass base=USD when you also need TTF_GAS or EUA_CO2. Although this guide focuses on CARBON_INT_ES, follow that rule if you later expand your request set.
- If you suspect a catalog change, query the symbol listing at /api/v1/symbols and verify CARBON_INT_ES exists and is available.
Local verification workflow
- Manually run the official cURL with your key to confirm firewall/proxy allowlisting.
- Log the full body for the first few runs in staging to confirm your parser matches the envelope.
- Unit test against the JSON examples above (success, mixed base, missing_symbols, and error) to ensure graceful degradation.
- Add a small metrics counter for success vs error envelopes and average response time to catch regressions early.
Security and key management
- Store YOUR_API_KEY in environment variables or a secrets manager; never commit to source control.
- Restrict who can read runtime configs and logs that might contain URLs with query parameters.
- If embedding the request in server logs, consider redacting the api_key parameter value.
Production readiness checklist
- Timeouts: Both connect and overall timeouts set.
- Retries: A capped retry with jitter for network timeouts; avoid infinite loops.
- Caching: Short TTL cache to lower error surface and latency.
- Validation: Numeric type checks for rates.CARBON_INT_ES; presence checks for dates and currencies maps.
- Monitoring: Alert if success=false occurs repeatedly or if symbol appears in missing_symbols.
FAQ
Q: What unit should I display for Spain Carbon Intensity?
A: gCO2/kWh. Read currencies.CARBON_INT_ES and prefer a unit label of gCO2/kWh in your UI.
Q: Why is base sometimes MIXED?
A: Non-currency series (like carbon intensity) can’t be normalized to a monetary base. Handle MIXED as a signal that units differ by symbol.
Q: I get success=true but there’s no CARBON_INT_ES in rates. What happened?
A: Check missing_symbols for diagnostic context. Your request succeeded but the symbol was unavailable for that response window.
Q: The response shows success=false with an error. Should I retry?
A: For transient errors, back off and retry with exponential jitter. If the error indicates catalog unavailability for CARBON_INT_ES, verify the current symbol list at /api/v1/symbols before retrying aggressively.
Q: Can I request multiple symbols at once?
A: Yes via the symbols parameter. If you later include TTF_GAS or EUA_CO2, do not pass base=USD in the same request.
Ready to integrate Spain Carbon Intensity in minutes? Create your key and start with the official examples: Register. For deeper reference, field definitions, and symbol catalog access, keep the Documentation open as you code.
Ready to get started?
Get your API key and start querying energy commodity prices in minutes.
Get API Key