Java Integration Guide
Integrate OilPriceAPI into your Java applications to access the latest available crude oil prices, Brent crude data, natural gas rates, and commodity market information. Source publication and refresh schedules vary by dataset. Perfect for enterprise applications, Spring Boot services, and Android development.
Requirements
- Java 11+ (for HttpClient) or Java 8+ (with OkHttp)
- Jackson or Gson for JSON parsing
Maven Dependencies
<!-- Jackson for JSON parsing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.0</version>
</dependency>
<!-- Optional: OkHttp for Java 8 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
Quick Start (Java 11+)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class OilPriceExample {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("OILPRICEAPI_KEY");
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD"))
.header("Authorization", "Token " + apiKey)
.header("Accept", "application/json")
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
Complete API Client
Create a reusable client for all OilPriceAPI endpoints:
package com.example.oilpriceapi;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class OilPriceApiClient {
private final String apiKey;
private final String baseUrl;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
public OilPriceApiClient(String apiKey) {
this.apiKey = apiKey != null ? apiKey : System.getenv("OILPRICEAPI_KEY");
this.baseUrl = "https://api.oilpriceapi.com/v1";
this.httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
this.objectMapper = new ObjectMapper();
}
// Data classes
public static class Price {
public String code;
public double price;
public String currency;
public String unit;
public String formatted;
@JsonProperty("created_at")
public String createdAt;
@JsonProperty("change_24h")
public Double change24h;
@JsonProperty("change_24h_pct")
public Double change24hPct;
}
public static class PriceResponse {
public String status;
public Price data;
}
public static class HistoricalPrice {
public String date;
public double open;
public double high;
public double low;
public double close;
public Long volume;
}
public static class HistoricalResponse {
public String status;
public HistoricalData data;
}
public static class HistoricalData {
public String code;
public String currency;
public String unit;
public List<HistoricalPrice> prices;
}
public static class ApiError extends RuntimeException {
public int statusCode;
public String errorCode;
public String message;
public ApiError(int statusCode, String errorCode, String message) {
super(message);
this.statusCode = statusCode;
this.errorCode = errorCode;
this.message = message;
}
}
// HTTP request methods
private <T> T get(String endpoint, Class<T> responseType) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + endpoint))
.header("Authorization", "Token " + apiKey)
.header("Accept", "application/json")
.header("X-Client-Name", "java-client")
.header("X-Client-Version", "1.0.0")
.GET()
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
throw new ApiError(response.statusCode(), "HTTP_ERROR", response.body());
}
return objectMapper.readValue(response.body(), responseType);
}
private <T> CompletableFuture<T> getAsync(String endpoint, Class<T> responseType) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + endpoint))
.header("Authorization", "Token " + apiKey)
.header("Accept", "application/json")
.GET()
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
try {
if (response.statusCode() >= 400) {
throw new ApiError(response.statusCode(), "HTTP_ERROR", response.body());
}
return objectMapper.readValue(response.body(), responseType);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
// API Methods
/**
* Get latest price for a commodity
*/
public Price getLatestPrice(String code) throws Exception {
String encoded = URLEncoder.encode(code, StandardCharsets.UTF_8);
PriceResponse response = get("/prices/latest?by_code=" + encoded, PriceResponse.class);
return response.data;
}
/**
* Get latest price asynchronously
*/
public CompletableFuture<Price> getLatestPriceAsync(String code) {
String encoded = URLEncoder.encode(code, StandardCharsets.UTF_8);
return getAsync("/prices/latest?by_code=" + encoded, PriceResponse.class)
.thenApply(response -> response.data);
}
/**
* Get historical prices
*/
public List<HistoricalPrice> getHistoricalPrices(String code, LocalDate startDate, LocalDate endDate)
throws Exception {
StringBuilder url = new StringBuilder("/prices/historical?by_code=");
url.append(URLEncoder.encode(code, StandardCharsets.UTF_8));
if (startDate != null) {
url.append("&start_date=").append(startDate);
}
if (endDate != null) {
url.append("&end_date=").append(endDate);
}
HistoricalResponse response = get(url.toString(), HistoricalResponse.class);
return response.data.prices;
}
/**
* Get all available commodities
*/
public List<Map<String, Object>> getCommodities() throws Exception {
return get("/commodities", List.class);
}
}
Usage Examples
Basic Usage
OilPriceApiClient client = new OilPriceApiClient(System.getenv("OILPRICEAPI_KEY"));
// Get WTI price
OilPriceApiClient.Price wti = client.getLatestPrice("WTI_USD");
System.out.printf("WTI: %s (%.2f%% change)%n",
wti.formatted, wti.change24hPct);
// Get Brent price
OilPriceApiClient.Price brent = client.getLatestPrice("BRENT_CRUDE_USD");
System.out.printf("Brent: %s%n", brent.formatted);
Async Requests
OilPriceApiClient client = new OilPriceApiClient(apiKey);
// Fetch multiple prices concurrently
CompletableFuture<OilPriceApiClient.Price> wtiFuture =
client.getLatestPriceAsync("WTI_USD");
CompletableFuture<OilPriceApiClient.Price> brentFuture =
client.getLatestPriceAsync("BRENT_CRUDE_USD");
CompletableFuture<OilPriceApiClient.Price> gasFuture =
client.getLatestPriceAsync("NATURAL_GAS_USD");
// Wait for all and process
CompletableFuture.allOf(wtiFuture, brentFuture, gasFuture)
.thenRun(() -> {
try {
System.out.println("WTI: " + wtiFuture.get().formatted);
System.out.println("Brent: " + brentFuture.get().formatted);
System.out.println("Natural Gas: " + gasFuture.get().formatted);
} catch (Exception e) {
e.printStackTrace();
}
})
.join();
Historical Data
import java.time.LocalDate;
OilPriceApiClient client = new OilPriceApiClient(apiKey);
// Get last 30 days of WTI prices
LocalDate endDate = LocalDate.now();
LocalDate startDate = endDate.minusDays(30);
List<OilPriceApiClient.HistoricalPrice> prices =
client.getHistoricalPrices("WTI_USD", startDate, endDate);
for (OilPriceApiClient.HistoricalPrice price : prices) {
System.out.printf("%s: Open=%.2f, Close=%.2f, High=%.2f, Low=%.2f%n",
price.date, price.open, price.close, price.high, price.low);
}
Spring Boot Integration
Configuration
@Configuration
public class OilPriceApiConfig {
@Value("${oilprice.api.key}")
private String apiKey;
@Bean
public OilPriceApiClient oilPriceApiClient() {
return new OilPriceApiClient(apiKey);
}
}
Service
@Service
public class PriceService {
private final OilPriceApiClient apiClient;
public PriceService(OilPriceApiClient apiClient) {
this.apiClient = apiClient;
}
public OilPriceApiClient.Price getCurrentWtiPrice() {
try {
return apiClient.getLatestPrice("WTI_USD");
} catch (Exception e) {
throw new RuntimeException("Failed to fetch WTI price", e);
}
}
@Cacheable(value = "prices", key = "#code")
public OilPriceApiClient.Price getPrice(String code) {
try {
return apiClient.getLatestPrice(code);
} catch (Exception e) {
throw new RuntimeException("Failed to fetch price for " + code, e);
}
}
}
Controller
@RestController
@RequestMapping("/api/prices")
public class PriceController {
private final PriceService priceService;
public PriceController(PriceService priceService) {
this.priceService = priceService;
}
@GetMapping("/{code}")
public ResponseEntity<OilPriceApiClient.Price> getPrice(@PathVariable String code) {
OilPriceApiClient.Price price = priceService.getPrice(code);
return ResponseEntity.ok(price);
}
@GetMapping("/wti")
public ResponseEntity<OilPriceApiClient.Price> getWtiPrice() {
return ResponseEntity.ok(priceService.getCurrentWtiPrice());
}
}
Error Handling
public OilPriceApiClient.Price getPrice(String code) {
try {
return apiClient.getLatestPrice(code);
} catch (OilPriceApiClient.ApiError e) {
switch (e.statusCode) {
case 401:
throw new UnauthorizedException("Invalid API key");
case 404:
throw new NotFoundException("Commodity not found: " + code);
case 429:
throw new RateLimitException("Rate limit exceeded. Try again later.");
default:
throw new ApiException("API error: " + e.message);
}
} catch (Exception e) {
throw new ApiException("Request failed: " + e.getMessage());
}
}
Retry with Exponential Backoff
public <T> T withRetry(Callable<T> operation, int maxRetries) {
int attempt = 0;
while (true) {
try {
return operation.call();
} catch (OilPriceApiClient.ApiError e) {
if (e.statusCode == 429 && attempt < maxRetries) {
attempt++;
long delay = (long) Math.pow(2, attempt) * 1000;
try {
Thread.sleep(delay);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted during retry", ie);
}
} else {
throw e;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// Usage
OilPriceApiClient.Price price = withRetry(
() -> apiClient.getLatestPrice("WTI_USD"),
3 // max retries
);
Common Commodity Codes
| Code | Description |
|---|---|
WTI_USD | West Texas Intermediate |
BRENT_CRUDE_USD | Brent Crude |
NATURAL_GAS_USD | Henry Hub Natural Gas |
HEATING_OIL_USD | Heating Oil |
DIESEL_USD | Ultra Low Sulfur Diesel |
GASOLINE_USD | RBOB Gasoline |
Related
- API Reference - Full endpoint documentation
- Error Codes - Complete error handling guide
- Rate Limits - Request limits by plan