Skip to content

Instantly share code, notes, and snippets.

@GeeWee
Created March 8, 2022 08:27
Show Gist options
  • Save GeeWee/0dcdb9fc0186b881bd084da849f16d99 to your computer and use it in GitHub Desktop.
Save GeeWee/0dcdb9fc0186b881bd084da849f16d99 to your computer and use it in GitHub Desktop.
Climatiq java example
import com.fasterxml.jackson.databind.ObjectMapper;
import models.ClimatiqEstimateResponse;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
// Example of how to use Java to use the climatiq API
// This example requires jackson and apache's HttpClient to be installed into the project
public class Main {
public static void main(String[] args) throws Exception {
try(CloseableHttpClient client = HttpClients.createDefault()){
//1. ---------------------- Make the request
HttpPost httpPost = new HttpPost("https://beta3.api.climatiq.io/estimate");
// Add the header with your API key
httpPost.addHeader("Authorization", "Bearer: YOUR_API_KEY_HERE");
// Send some JSON. In a bigger example you would construct this JSON via Java objects
var requestJson = "{\n" +
"\t\"emission_factor\": {\n" +
"\t\t\"id\": \"accommodation_type_hotel_stay\",\n" +
"\t\t\"region\": \"CA\"\n" +
"\t},\n" +
"\t\"parameters\": {\n" +
"\t\t\"number\": 2\n" +
"\t}\n" +
"}";
httpPost.setEntity(new StringEntity(requestJson));
var httpResponse = client.execute(httpPost);
// 2. -------------------- Parse the response
System.out.println(httpResponse); // Print out the status code
var httpBody = EntityUtils.toString(httpResponse.getEntity());
System.out.println(httpBody); // Print out the raw body
// Transform the raw body into a Java object
ObjectMapper objectMapper = new ObjectMapper();
var parsedResponse = objectMapper.readValue(httpBody, ClimatiqEstimateResponse.class);
System.out.println(parsedResponse.co2e);
}
}
}
package models;
public class ClimatiqEstimateResponse {
public double co2e;
public String co2e_unit;
public String co2e_calculation_method;
public String co2e_calculation_origin;
public EmissionFactor emission_factor;
public ConstituentGases constituent_gases;
}
package models;
public class ConstituentGases {
public double co2e_total;
public Object co2e_other;
public Object co2;
public Object ch4;
public Object n2o;
}
package models;
public class EmissionFactor {
public String id;
public String source;
public String year;
public String region;
public String category;
public String lca_activity;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment