Skip to main content
Java Integration

Java Oil Price API

Integrate real-time oil and commodity prices into your Java applications. Enterprise-ready with Spring Boot, async processing, and comprehensive error handling.

Quick Start

1. Add Dependencies

<!-- Maven dependencies -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>

2. Java Features

  • Enterprise-grade error handling
  • Spring Boot integration
  • Async and caching support

Basic Integration

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class OilPriceAPI {
    private static final String BASE_URL = "https://api.oilpriceapi.com";
    private final String apiKey;
    private final Gson gson;
    
    public OilPriceAPI(String apiKey) {
        this.apiKey = apiKey;
        this.gson = new Gson();
    }
    
    public ApiResponse getBrentPrice() throws IOException {
        return makeRequest("/prices");
    }
    
    public ApiResponse getCommodityHealth() throws IOException {
        return makeRequest("/health");
    }
    
    public CommodityPrice getWTIPrice() throws IOException {
        ApiResponse healthResponse = getCommodityHealth();
        JsonObject healthData = JsonParser.parseString(healthResponse.getBody()).getAsJsonObject();
        
        JsonObject metrics = healthData.getAsJsonObject("metrics");
        if (metrics == null) return null;
        
        JsonObject commodityHealth = metrics.getAsJsonObject("commodity_health");
        if (commodityHealth == null) return null;
        
        JsonObject wtiData = commodityHealth.getAsJsonObject("WTI_USD");
        if (wtiData == null) return null;
        
        double latestPrice = wtiData.get("latest_price").getAsDouble();
        String lastUpdate = wtiData.get("last_update").getAsString();
        
        return new CommodityPrice(
            latestPrice / 100.0, // Convert from cents
            lastUpdate,
            "USD",
            "barrel"
        );
    }
    
    public Map<String, CommodityPrice> getAllCommodities() throws IOException {
        Map<String, CommodityPrice> commodities = new HashMap<>();
        
        // Get Brent from prices endpoint
        ApiResponse brentResponse = getBrentPrice();
        JsonObject brentData = JsonParser.parseString(brentResponse.getBody()).getAsJsonObject();
        JsonObject brentPriceData = brentData.getAsJsonObject("data");
        
        if (brentPriceData != null) {
            commodities.put("brent_crude", new CommodityPrice(
                brentPriceData.get("price").getAsDouble(),
                brentPriceData.get("timestamp").getAsString(),
                brentPriceData.get("currency").getAsString(),
                "barrel"
            ));
        }
        
        // Get other commodities from health endpoint
        ApiResponse healthResponse = getCommodityHealth();
        JsonObject healthData = JsonParser.parseString(healthResponse.getBody()).getAsJsonObject();
        JsonObject metrics = healthData.getAsJsonObject("metrics");
        
        if (metrics != null) {
            JsonObject commodityHealth = metrics.getAsJsonObject("commodity_health");
            if (commodityHealth != null) {
                for (String key : commodityHealth.keySet()) {
                    JsonObject commodity = commodityHealth.getAsJsonObject(key);
                    if (commodity.has("latest_price")) {
                        double scale = isCurrencyPair(key) ? 10000.0 : 100.0;
                        double price = commodity.get("latest_price").getAsDouble() / scale;
                        
                        commodities.put(key.toLowerCase(), new CommodityPrice(
                            price,
                            commodity.get("last_update").getAsString(),
                            "USD",
                            getUnit(key)
                        ));
                    }
                }
            }
        }
        
        return commodities;
    }
    
    private ApiResponse makeRequest(String endpoint) throws IOException {
        URL url = new URL(BASE_URL + endpoint);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // Set request properties
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Token " + apiKey);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(10000); // 10 seconds
        connection.setReadTimeout(10000);
        
        int responseCode = connection.getResponseCode();
        
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                responseCode >= 200 && responseCode < 300 ? 
                connection.getInputStream() : connection.getErrorStream()))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        return new ApiResponse(responseCode, response.toString());
    }
    
    private boolean isCurrencyPair(String commodityKey) {
        return commodityKey.equals("EUR_USD") || commodityKey.equals("GBP_USD");
    }
    
    private String getUnit(String commodityKey) {
        Map<String, String> units = new HashMap<>();
        units.put("WTI_USD", "barrel");
        units.put("NATURAL_GAS_USD", "MMBtu");
        units.put("GOLD_USD", "ounce");
        units.put("EUR_USD", "USD");
        units.put("GBP_USD", "USD");
        
        return units.getOrDefault(commodityKey, "unit");
    }
    
    // Data classes
    public static class ApiResponse {
        private final int statusCode;
        private final String body;
        
        public ApiResponse(int statusCode, String body) {
            this.statusCode = statusCode;
            this.body = body;
        }
        
        public int getStatusCode() { return statusCode; }
        public String getBody() { return body; }
        public boolean isSuccessful() { return statusCode >= 200 && statusCode < 300; }
    }
    
    public static class CommodityPrice {
        private final double price;
        private final String timestamp;
        private final String currency;
        private final String unit;
        
        public CommodityPrice(double price, String timestamp, String currency, String unit) {
            this.price = price;
            this.timestamp = timestamp;
            this.currency = currency;
            this.unit = unit;
        }
        
        // Getters
        public double getPrice() { return price; }
        public String getTimestamp() { return timestamp; }
        public String getCurrency() { return currency; }
        public String getUnit() { return unit; }
        
        @Override
        public String toString() {
            return String.format("%.2f %s per %s (updated: %s)", 
                price, currency, unit, timestamp);
        }
    }
    
    // Usage example
    public static void main(String[] args) {
        try {
            OilPriceAPI api = new OilPriceAPI("YOUR_API_KEY_HERE");
            
            // Get Brent crude price
            ApiResponse brentResponse = api.getBrentPrice();
            if (brentResponse.isSuccessful()) {
                System.out.println("Brent Response: " + brentResponse.getBody());
            }
            
            // Get WTI price
            CommodityPrice wtiPrice = api.getWTIPrice();
            if (wtiPrice != null) {
                System.out.println("WTI: " + wtiPrice);
            }
            
            // Get all commodities
            Map<String, CommodityPrice> allCommodities = api.getAllCommodities();
            allCommodities.forEach((name, price) -> 
                System.out.println(name.toUpperCase() + ": " + price));
                
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Spring Boot Integration

Production-ready Spring Boot service with caching and REST endpoints:

// pom.xml dependencies
/*
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>
*/

package com.example.oilprices;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableCaching
public class OilPriceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OilPriceApplication.class, args);
    }
}

@Service
public class OilPriceService {
    private static final String BASE_URL = "https://api.oilpriceapi.com";
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;
    private final String apiKey;
    
    public OilPriceService(@Value("${oil.price.api.key}") String apiKey) {
        this.apiKey = apiKey;
        this.objectMapper = new ObjectMapper();
        this.httpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();
    }
    
    @Cacheable(value = "brentPrice", unless = "#result == null")
    public PriceResponse getBrentPrice() throws OilPriceException {
        try {
            Request request = new Request.Builder()
                .url(BASE_URL + "/prices")
                .header("Authorization", "Token " + apiKey)
                .header("Content-Type", "application/json")
                .build();
                
            try (Response response = httpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new OilPriceException("HTTP " + response.code() + ": " + response.message());
                }
                
                String responseBody = response.body().string();
                return objectMapper.readValue(responseBody, PriceResponse.class);
            }
        } catch (IOException e) {
            throw new OilPriceException("Failed to fetch Brent price", e);
        }
    }
    
    @Cacheable(value = "commodityHealth", unless = "#result == null")
    public HealthResponse getCommodityHealth() throws OilPriceException {
        try {
            Request request = new Request.Builder()
                .url(BASE_URL + "/health")
                .header("Authorization", "Token " + apiKey)
                .header("Content-Type", "application/json")
                .build();
                
            try (Response response = httpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new OilPriceException("HTTP " + response.code() + ": " + response.message());
                }
                
                String responseBody = response.body().string();
                return objectMapper.readValue(responseBody, HealthResponse.class);
            }
        } catch (IOException e) {
            throw new OilPriceException("Failed to fetch commodity health", e);
        }
    }
    
    @Cacheable(value = "allCommodities", unless = "#result.isEmpty()")
    public Map<String, CommodityPrice> getAllCommodities() throws OilPriceException {
        Map<String, CommodityPrice> commodities = new HashMap<>();
        
        // Get Brent price
        PriceResponse brentResponse = getBrentPrice();
        if (brentResponse.getData() != null) {
            commodities.put("brent_crude", new CommodityPrice(
                brentResponse.getData().getPrice(),
                brentResponse.getData().getTimestamp(),
                brentResponse.getData().getCurrency(),
                "barrel"
            ));
        }
        
        // Get other commodities from health endpoint
        HealthResponse healthResponse = getCommodityHealth();
        if (healthResponse.getMetrics() != null && 
            healthResponse.getMetrics().getCommodityHealth() != null) {
            
            Map<String, JsonNode> healthData = healthResponse.getMetrics().getCommodityHealth();
            
            healthData.forEach((key, data) -> {
                if (data.has("latest_price")) {
                    double scale = isCurrencyPair(key) ? 10000.0 : 100.0;
                    double price = data.get("latest_price").asDouble() / scale;
                    
                    commodities.put(key.toLowerCase(), new CommodityPrice(
                        price,
                        data.get("last_update").asText(),
                        "USD",
                        getUnit(key)
                    ));
                }
            });
        }
        
        return commodities;
    }
    
    public CommodityPrice getCommodityPrice(String commodity) throws OilPriceException {
        Map<String, CommodityPrice> allPrices = getAllCommodities();
        CommodityPrice price = allPrices.get(commodity.toLowerCase());
        
        if (price == null) {
            throw new OilPriceException("Commodity not found: " + commodity);
        }
        
        return price;
    }
    
    private boolean isCurrencyPair(String commodityKey) {
        return "EUR_USD".equals(commodityKey) || "GBP_USD".equals(commodityKey);
    }
    
    private String getUnit(String commodityKey) {
        Map<String, String> units = Map.of(
            "WTI_USD", "barrel",
            "NATURAL_GAS_USD", "MMBtu",
            "GOLD_USD", "ounce",
            "EUR_USD", "USD",
            "GBP_USD", "USD"
        );
        return units.getOrDefault(commodityKey, "unit");
    }
}

// REST Controller
@RestController
@RequestMapping("/api/oil-prices")
@CrossOrigin(origins = "*")
public class OilPriceController {
    private final OilPriceService oilPriceService;
    
    public OilPriceController(OilPriceService oilPriceService) {
        this.oilPriceService = oilPriceService;
    }
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllPrices() {
        try {
            Map<String, CommodityPrice> prices = oilPriceService.getAllCommodities();
            Map<String, Object> response = Map.of(
                "status", "success",
                "data", prices,
                "timestamp", LocalDateTime.now()
            );
            return ResponseEntity.ok(response);
        } catch (OilPriceException e) {
            Map<String, Object> errorResponse = Map.of(
                "status", "error",
                "message", e.getMessage(),
                "timestamp", LocalDateTime.now()
            );
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    @GetMapping("/{commodity}")
    public ResponseEntity<Map<String, Object>> getCommodityPrice(@PathVariable String commodity) {
        try {
            CommodityPrice price = oilPriceService.getCommodityPrice(commodity);
            Map<String, Object> response = Map.of(
                "status", "success",
                "commodity", commodity,
                "data", price,
                "timestamp", LocalDateTime.now()
            );
            return ResponseEntity.ok(response);
        } catch (OilPriceException e) {
            Map<String, Object> errorResponse = Map.of(
                "status", "error",
                "message", e.getMessage(),
                "timestamp", LocalDateTime.now()
            );
            return ResponseEntity.status(e.getMessage().contains("not found") ? 404 : 500)
                .body(errorResponse);
        }
    }
    
    @GetMapping("/brent")
    public ResponseEntity<PriceResponse> getBrentPrice() {
        try {
            PriceResponse response = oilPriceService.getBrentPrice();
            return ResponseEntity.ok(response);
        } catch (OilPriceException e) {
            return ResponseEntity.status(500).build();
        }
    }
}

// Data Transfer Objects
public class PriceResponse {
    private String status;
    private PriceData data;
    
    // Getters and setters
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public PriceData getData() { return data; }
    public void setData(PriceData data) { this.data = data; }
}

public class PriceData {
    private double price;
    private String timestamp;
    private String currency;
    private String unit;
    
    // Getters and setters
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public String getTimestamp() { return timestamp; }
    public void setTimestamp(String timestamp) { this.timestamp = timestamp; }
    public String getCurrency() { return currency; }
    public void setCurrency(String currency) { this.currency = currency; }
    public String getUnit() { return unit; }
    public void setUnit(String unit) { this.unit = unit; }
}

public class HealthResponse {
    private String status;
    private Metrics metrics;
    
    // Getters and setters
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public Metrics getMetrics() { return metrics; }
    public void setMetrics(Metrics metrics) { this.metrics = metrics; }
}

public class Metrics {
    @JsonProperty("commodity_health")
    private Map<String, JsonNode> commodityHealth;
    
    public Map<String, JsonNode> getCommodityHealth() { return commodityHealth; }
    public void setCommodityHealth(Map<String, JsonNode> commodityHealth) { 
        this.commodityHealth = commodityHealth; 
    }
}

public class CommodityPrice {
    private final double price;
    private final String timestamp;
    private final String currency;
    private final String unit;
    
    public CommodityPrice(double price, String timestamp, String currency, String unit) {
        this.price = price;
        this.timestamp = timestamp;
        this.currency = currency;
        this.unit = unit;
    }
    
    // Getters
    public double getPrice() { return price; }
    public String getTimestamp() { return timestamp; }
    public String getCurrency() { return currency; }
    public String getUnit() { return unit; }
}

// Custom Exception
public class OilPriceException extends Exception {
    public OilPriceException(String message) {
        super(message);
    }
    
    public OilPriceException(String message, Throwable cause) {
        super(message, cause);
    }
}

// application.properties
/*
oil.price.api.key=YOUR_API_KEY_HERE
spring.cache.type=simple
logging.level.com.example.oilprices=DEBUG
*/

Async Processing with OkHttp

High-performance async client with CompletableFuture:

import okhttp3.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class AsyncOilPriceClient {
    private static final String BASE_URL = "https://api.oilpriceapi.com";
    private final OkHttpClient httpClient;
    private final Gson gson;
    private final String apiKey;
    
    public AsyncOilPriceClient(String apiKey) {
        this.apiKey = apiKey;
        this.gson = new GsonBuilder()
            .setPrettyPrinting()
            .create();
        this.httpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build();
    }
    
    public CompletableFuture<PriceResponse> getBrentPriceAsync() {
        CompletableFuture<PriceResponse> future = new CompletableFuture<>();
        
        Request request = buildRequest("/prices");
        
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                future.completeExceptionally(e);
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) {
                        future.completeExceptionally(new IOException("HTTP " + response.code()));
                        return;
                    }
                    
                    String json = responseBody.string();
                    PriceResponse priceResponse = gson.fromJson(json, PriceResponse.class);
                    future.complete(priceResponse);
                } catch (Exception e) {
                    future.completeExceptionally(e);
                }
            }
        });
        
        return future;
    }
    
    public CompletableFuture<HealthResponse> getHealthAsync() {
        CompletableFuture<HealthResponse> future = new CompletableFuture<>();
        
        Request request = buildRequest("/health");
        
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                future.completeExceptionally(e);
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) {
                        future.completeExceptionally(new IOException("HTTP " + response.code()));
                        return;
                    }
                    
                    String json = responseBody.string();
                    HealthResponse healthResponse = gson.fromJson(json, HealthResponse.class);
                    future.complete(healthResponse);
                } catch (Exception e) {
                    future.completeExceptionally(e);
                }
            }
        });
        
        return future;
    }
    
    public CompletableFuture<CombinedPriceData> getAllPricesAsync() {
        CompletableFuture<PriceResponse> brentFuture = getBrentPriceAsync();
        CompletableFuture<HealthResponse> healthFuture = getHealthAsync();
        
        return CompletableFuture.allOf(brentFuture, healthFuture)
            .thenApply(v -> {
                try {
                    PriceResponse brentResponse = brentFuture.get();
                    HealthResponse healthResponse = healthFuture.get();
                    
                    return new CombinedPriceData(brentResponse, healthResponse);
                } catch (Exception e) {
                    throw new RuntimeException("Failed to combine price data", e);
                }
            });
    }
    
    private Request buildRequest(String endpoint) {
        return new Request.Builder()
            .url(BASE_URL + endpoint)
            .header("Authorization", "Token " + apiKey)
            .header("Content-Type", "application/json")
            .header("User-Agent", "OilPriceAPI-Java-Client/1.0")
            .build();
    }
    
    public void close() {
        httpClient.dispatcher().executorService().shutdown();
        httpClient.connectionPool().evictAll();
    }
    
    // Usage example with async processing
    public static void main(String[] args) {
        AsyncOilPriceClient client = new AsyncOilPriceClient("YOUR_API_KEY_HERE");
        
        try {
            // Get all prices asynchronously
            CompletableFuture<CombinedPriceData> pricesFuture = client.getAllPricesAsync();
            
            pricesFuture.thenAccept(data -> {
                System.out.println("=== Live Oil Prices ===");
                
                // Print Brent crude price
                if (data.getBrentResponse() != null && data.getBrentResponse().getData() != null) {
                    PriceData brent = data.getBrentResponse().getData();
                    System.out.printf("Brent Crude: $%.2f/%s%n", 
                        brent.getPrice(), brent.getUnit());
                }
                
                // Print WTI and other commodities from health data
                data.extractCommodityPrices().forEach((name, price) -> {
                    System.out.printf("%s: $%.2f/%s%n", 
                        name.replace("_", " ").toUpperCase(), 
                        price.getPrice(), 
                        price.getUnit());
                });
                
            }).exceptionally(throwable -> {
                System.err.println("Error fetching prices: " + throwable.getMessage());
                throwable.printStackTrace();
                return null;
            }).join(); // Wait for completion
            
        } finally {
            client.close();
        }
    }
}

class CombinedPriceData {
    private final PriceResponse brentResponse;
    private final HealthResponse healthResponse;
    
    public CombinedPriceData(PriceResponse brentResponse, HealthResponse healthResponse) {
        this.brentResponse = brentResponse;
        this.healthResponse = healthResponse;
    }
    
    public PriceResponse getBrentResponse() { return brentResponse; }
    public HealthResponse getHealthResponse() { return healthResponse; }
    
    public Map<String, CommodityPrice> extractCommodityPrices() {
        Map<String, CommodityPrice> prices = new HashMap<>();
        
        if (healthResponse != null && healthResponse.getMetrics() != null) {
            Map<String, Object> commodityHealth = healthResponse.getMetrics().getCommodityHealth();
            
            if (commodityHealth != null) {
                commodityHealth.forEach((key, value) -> {
                    if (value instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> data = (Map<String, Object>) value;
                        
                        if (data.containsKey("latest_price")) {
                            double latestPrice = ((Number) data.get("latest_price")).doubleValue();
                            double scale = isCurrencyPair(key) ? 10000.0 : 100.0;
                            double price = latestPrice / scale;
                            
                            prices.put(key.toLowerCase(), new CommodityPrice(
                                price,
                                (String) data.get("last_update"),
                                "USD",
                                getUnit(key)
                            ));
                        }
                    }
                });
            }
        }
        
        return prices;
    }
    
    private boolean isCurrencyPair(String key) {
        return "EUR_USD".equals(key) || "GBP_USD".equals(key);
    }
    
    private String getUnit(String key) {
        Map<String, String> units = Map.of(
            "WTI_USD", "barrel",
            "NATURAL_GAS_USD", "MMBtu",
            "GOLD_USD", "ounce",
            "EUR_USD", "USD",
            "GBP_USD", "USD"
        );
        return units.getOrDefault(key, "unit");
    }
}

Available Commodities

Brent Crude Oil

North Sea Brent crude oil, the global benchmark for oil pricing representing ~60% of internationally traded crude oil.

API Field: BRENT_CRUDE_USD
Unit: barrel
Endpoint: /prices

WTI Crude Oil

West Texas Intermediate crude oil, the primary benchmark for North American oil markets and NYMEX futures.

API Field: WTI_USD
Unit: barrel
Endpoint: /health

Dubai Crude Oil

Dubai crude oil benchmark for Middle Eastern crude oil pricing and Asian markets.

API Field: DUBAI_CRUDE_USD
Unit: barrel
Endpoint: /health

Natural Gas

NYMEX Henry Hub natural gas futures, the primary pricing benchmark for North American natural gas markets.

API Field: NATURAL_GAS_USD
Unit: MMBtu
Endpoint: /health

WAHA Natural Gas

WAHA Hub natural gas spot price from the Permian Basin. Regional pricing benchmark reflecting Midland-area production and pipeline capacity constraints. Can trade at negative prices during pipeline congestion.

API Field: NATURAL_GAS_WAHA
Unit: MMBtu
Endpoint: /prices

Natural Gas (UK)

UK natural gas pricing in British pence per therm.

API Field: NATURAL_GAS_GBP
Unit: GBp/thm
Endpoint: /health

Dutch TTF Gas

Dutch Title Transfer Facility (TTF) natural gas futures, the European gas pricing benchmark.

API Field: DUTCH_TTF_EUR
Unit: EUR/MWh
Endpoint: /health

JKM LNG

Japan/Korea Marker (JKM) LNG futures, the primary pricing benchmark for Asian liquefied natural gas markets.

API Field: JKM_LNG_USD
Unit: MMBtu
Endpoint: /health

Gasoline RBOB

Reformulated Blendstock for Oxygenate Blending (RBOB) gasoline futures.

API Field: GASOLINE_RBOB_USD
Unit: gallon
Endpoint: /health

Propane

Mont Belvieu propane spot price — the key U.S. NGL benchmark for residential heating, petrochemical feedstock, and agricultural drying.

API Field: PROPANE_MONT_BELVIEU_USD
Unit: gallon
Endpoint: /health

Heating Oil

No. 2 heating oil futures, a key refined petroleum product for heating and industrial use.

API Field: HEATING_OIL_USD
Unit: gallon
Endpoint: /health

Newcastle Coal (API6)

Newcastle Coal (API6) — the Asian thermal coal benchmark price per metric ton, widely used for pricing coal imports in Asia-Pacific.

API Field: NEWCASTLE_COAL_USD
Unit: MT
Endpoint: /health

Coking Coal

Metallurgical (coking) coal price per metric ton, essential feedstock for steelmaking in blast furnaces.

API Field: COKING_COAL_USD
Unit: MT
Endpoint: /health

Central Appalachian Coal

Central Appalachian (CAPP) thermal coal spot price, a key US East Coast coal benchmark from EIA weekly data.

API Field: CAPP_COAL_USD
Unit: short_ton
Endpoint: /health

Powder River Basin Coal

Powder River Basin (Wyoming) thermal coal spot price, the lowest-cost US coal basin. EIA weekly data.

API Field: PRB_COAL_USD
Unit: short_ton
Endpoint: /health

Illinois Basin Coal

Illinois Basin thermal coal spot price, a major US interior coal benchmark. EIA weekly data.

API Field: ILLINOIS_COAL_USD
Unit: short_ton
Endpoint: /health

US Natural Gas Storage

US weekly natural gas storage inventory levels in billion cubic feet (Bcf), a key supply indicator from EIA.

API Field: NATURAL_GAS_STORAGE
Unit: Bcf
Endpoint: /health

Gold

Gold futures pricing, a key precious metal and safe-haven asset.

API Field: GOLD_USD
Unit: ounce
Endpoint: /health

Silver

Silver spot price, a precious metal used in jewelry, electronics, solar panels, and as an investment asset.

API Field: SILVER_USD
Unit: ounce
Endpoint: /health

Platinum

Platinum spot price, a precious metal critical for automotive catalytic converters, jewelry, and industrial applications.

API Field: PLATINUM_USD
Unit: ounce
Endpoint: /health

Palladium

Palladium spot price, a precious metal essential for gasoline vehicle catalytic converters and electronics.

API Field: PALLADIUM_USD
Unit: ounce
Endpoint: /health

EUR/USD

Euro to US Dollar exchange rate, the most traded currency pair globally.

API Field: EUR_USD
Unit: USD
Endpoint: /health

GBP/USD

British Pound to US Dollar exchange rate, also known as "Cable".

API Field: GBP_USD
Unit: USD
Endpoint: /health

USD/CNY

US Dollar to Chinese Yuan exchange rate, critical for global commodity trade and Asian energy markets.

API Field: USD_CNY
Unit: CNY
Endpoint: /health

VLSFO Marine Fuel

Very Low Sulfur Fuel Oil Singapore benchmark price, IMO 2020 compliant marine fuel for commercial shipping. For port-specific bunker prices, use the /v1/bunker-fuels API.

API Field: VLSFO_USD
Unit: MT
Endpoint: /health

Marine Gas Oil 0.5%S

Marine Gas Oil Singapore benchmark price with 0.5% sulfur content, compliant with IMO 2020 emission standards. For port-specific bunker prices, use the /v1/bunker-fuels API.

API Field: MGO_05S_USD
Unit: MT
Endpoint: /health

Heavy Fuel Oil 380

Heavy Fuel Oil with 380 cSt viscosity, traditional marine bunker fuel for large vessels.

API Field: HFO_380_USD
Unit: MT
Endpoint: /health

Heavy Fuel Oil 180

Heavy Fuel Oil with 180 cSt viscosity, medium-grade marine bunker fuel for shipping.

API Field: HFO_180_USD
Unit: MT
Endpoint: /health

Azeri Light Crude Oil

Azeri Light (BTC) Crude Oil — key Caspian/Mediterranean benchmark transported via Baku-Tbilisi-Ceyhan pipeline, important for European refiners.

API Field: AZERI_LIGHT_USD
Unit: barrel
Endpoint: /prices

Tapis Crude Oil

Malaysian Tapis Crude Oil - Light Sweet Asian benchmark oil used for pricing in Southeast Asia.

API Field: TAPIS_CRUDE_USD
Unit: barrel
Endpoint: /health

Western Canadian Select

Western Canadian Select heavy crude oil, the primary Canadian oil benchmark.

API Field: WCS_CRUDE_USD
Unit: barrel
Endpoint: /health

Urals Crude Oil

Russian Urals crude oil, the primary Russian export grade and Eastern European benchmark.

API Field: URALS_CRUDE_USD
Unit: barrel
Endpoint: /health

OPEC Basket

OPEC Reference Basket — a weighted average of petroleum blends from OPEC member countries, used as a benchmark for OPEC production decisions.

API Field: OPEC_BASKET_USD
Unit: barrel
Endpoint: /health

Basrah Medium Crude

Iraqi Basrah Medium crude oil — a key Middle Eastern export grade and benchmark for Asian and European refiners.

API Field: BASRAH_MEDIUM_USD
Unit: barrel
Endpoint: /health

Diesel (Gulf Coast)

U.S. Gulf Coast Ultra-Low Sulfur No 2 Diesel spot price, critical for transportation and logistics.

API Field: DIESEL_USD
Unit: gallon
Endpoint: /health

ULSD Diesel (NY Harbor)

Ultra Low Sulfur No 2 Diesel spot price FOB New York Harbor, the NYMEX delivery standard.

API Field: ULSD_DIESEL_USD
Unit: gallon
Endpoint: /health

Jet Fuel

Kerosene-type jet fuel spot price, essential for aviation industry fuel costs and planning.

API Field: JET_FUEL_USD
Unit: gallon
Endpoint: /health

Ethanol

Ethanol fuel pricing, renewable biofuel component for gasoline blending.

API Field: ETHANOL_USD
Unit: gallon
Endpoint: /health

ICE Gasoil (Rotterdam)

ICE Low Sulphur Gasoil futures — the European diesel benchmark delivered in Amsterdam-Rotterdam-Antwerp (ARA). Used for pricing diesel, heating oil, and jet fuel across Europe.

API Field: GASOIL_USD
Unit: tonne
Endpoint: /health

Jet A-1 (Northwest Europe)

Jet A-1 aviation fuel spot price for Northwest Europe (NWE basis). The primary benchmark for European airline fuel procurement and aviation fuel hedging.

API Field: JET_A1_NWE_USD
Unit: barrel
Endpoint: /health

Singapore Jet Kerosene

Singapore Platts Jet Kerosene (Jet A-1) spot price — the Asia-Pacific aviation fuel benchmark used by airlines across Asia, Australia, and the Middle East.

API Field: SINGAPORE_JET_KEROSENE_USD
Unit: barrel
Endpoint: /health

Singapore Mogas 92

Singapore Platts Mogas 92 RON gasoline benchmark — the primary Asia-Pacific gasoline reference price used for gasoline trading and pricing across Asia.

API Field: SINGAPORE_MOGAS_92_USD
Unit: MT
Endpoint: /health

Jet Fuel (A4A/Argus Index)

Airlines for America (A4A) Jet Fuel Cost Index based on Argus spot prices from Chicago, Houston, Los Angeles, and New York. The U.S. airline industry standard for fuel cost benchmarking.

API Field: JET_FUEL_A4A_USD
Unit: gallon
Endpoint: /health

Asphalt

Asphalt (bitumen) spot price per metric ton, a refined petroleum product used in road construction and roofing.

API Field: ASPHALT_USD
Unit: metric_ton
Endpoint: /health

Naphtha

Naphtha spot price per metric ton, a light petroleum distillate used as a petrochemical feedstock and gasoline blending component.

API Field: NAPHTHA_USD
Unit: metric_ton
Endpoint: /health

Methanol

Methanol (methyl alcohol) spot price per metric ton, a key chemical feedstock used in plastics, fuels, and industrial applications.

API Field: METHANOL_USD
Unit: metric_ton
Endpoint: /health

Ethylene

Ethylene spot price per metric ton, the world's most-produced organic compound and foundational petrochemical feedstock for plastics.

API Field: ETHYLENE_USD
Unit: metric_ton
Endpoint: /health

Polyethylene

Polyethylene spot price per metric ton, the world's most widely used plastic polymer derived from ethylene.

API Field: POLYETHYLENE_USD
Unit: metric_ton
Endpoint: /health

Polypropylene

Polypropylene spot price per metric ton, a versatile thermoplastic polymer used in packaging, automotive parts, and textiles.

API Field: POLYPROPYLENE_USD
Unit: metric_ton
Endpoint: /health

Urea

Urea (fertilizer-grade) spot price per metric ton, a nitrogen-based fertilizer and industrial chemical derived from natural gas.

API Field: UREA_USD
Unit: metric_ton
Endpoint: /health

Ammonia

Ammonia spot price per metric ton, a key nitrogen feedstock for fertilizers and a growing green hydrogen carrier.

API Field: AMMONIA_USD
Unit: metric_ton
Endpoint: /health

Biodiesel

Biodiesel spot price per gallon, a renewable fuel produced from vegetable oils and animal fats, used as a diesel substitute or blending component.

API Field: BIODIESEL_USD
Unit: gallon
Endpoint: /health

EU Carbon Allowances

European Union Emissions Trading System (EU ETS) carbon allowance pricing.

API Field: EU_CARBON_EUR
Unit: tCO2
Endpoint: /health

UK Carbon Allowances

UK Emissions Trading Scheme (UK ETS) carbon allowance pricing. Post-Brexit separate market from EU ETS.

API Field: UK_CARBON_GBP
Unit: tCO2
Endpoint: /health

International Rig Count

Monthly active drilling rig count for international markets outside North America, sourced from Baker Hughes.

API Field: INTERNATIONAL_RIG_COUNT
Unit: rigs
Endpoint: /health

US Rig Count

Weekly active drilling rig count for the United States from Baker Hughes, the industry standard for tracking US drilling activity across all major basins.

API Field: US_RIG_COUNT
Unit: rigs
Endpoint: /health

Java Best Practices

Error Handling

  • Use custom exceptions for API errors
  • Implement proper resource management
  • Log with appropriate levels

Performance

  • Use connection pooling with OkHttp
  • Implement caching with Spring Cache
  • Use async processing for concurrent requests

Ready to Start Building?

Get your free API key and start integrating real-time commodity prices into your Java applications today.