How to get live (spot) energy price using API in Java?

< Back to Guides

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. To get live energy price using Java, we offer two sample code snippets using different method. Methods includes using OkHttp, and Unirest.

Instructions

  1. Get a free API key to use by signing up at energypriceapi.com and replace REPLACE_ME with your API key.
  2. Update base value to a currency or remove this query param.
  3. Update currencies value to a list of values or remove this query param.

For 2 and 3, you can find this documented at Offical Documentation

 

Using OkHttp to fetch live energy price in Java

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
Request request = new Request.Builder()
  .url("https://api.energypriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=BRENT,WTI,NATURALGAS")
  .method("GET", null)
  .build();
Response response = client.newCall(request).execute();

 

Using Unirest to fetch live energy price

Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.get("https://api.energypriceapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=BRENT,WTI,NATURALGAS")
  .asString();