Production Total
UPDATED Thursday July 15, 10:08 PM PST
HTTP Request
GET https://wprice.io/api/v1/present/generation/production
This endpoint retrieves the last 24h of power consumption and production breakdown of an area, which represents the physical origin of electricity broken down by production type. It can either be queried by zone identifier or by geolocation. The resolution is 15 minutes (sampled).
Requires an API Key
This feature is only available to WattPricer Account-holders.
#
Query ParametersParameter | Description | Examples |
---|---|---|
zone_key | A string representing the zone identifier. We use a combination of ISO 3166-1 alpha-2 country codes, ISO 3166-2 country subdivision code, and where applicable, ISO 639-1 language codes for our locale codes. See the /zones endpoint for a list of valid zones. | US-MISO |
as_csv (OPTIONAL) | Boolean indicating whether to return the data in CSV format. | true |
#
Code samples- cURL
- C#
- Java
- JS
- Node
- ObjC
- PHP
- Python
- R
- Ruby
- Rust
- Scala
- TS
cURL command
@ECHO OFF
curl -v -X GET "https://wprice.io/api/v1/present/generation/production?zone_key={string}&as_csv={boolean}"-H "x-api-key: {subscription key}"
--data-ascii "{body}"
C-sharp code
using System;using System.Net.Http.Headers;using System.Text;using System.Net.Http;using System.Web;
namespace CSHttpClientSample{ static class Program { static void Main() { MakeRequest(); Console.WriteLine("Hit ENTER to exit..."); Console.ReadLine(); } static async void MakeRequest() { var client = new HttpClient(); var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers client.DefaultRequestHeaders.Add("x-api-key", "{subscription key}");
// Request parameters queryString["zone_key"] = "{string}"; queryString["as_csv"] = "{boolean}"; var uri = "https://wprice.io/api/v1/present/generation/production?" + queryString;
var response = await client.GetAsync(uri); } }}
Java code
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)import java.net.URI;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.utils.URIBuilder;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;
public class JavaSample { public static void main(String[] args) { HttpClient httpclient = HttpClients.createDefault();
try { URIBuilder builder = new URIBuilder("https://wprice.io/api/v1/present/generation/production");
builder.setParameter("zone_key", "{string}"); builder.setParameter("as_csv", "{boolean}");
URI uri = builder.build(); HttpGet request = new HttpGet(uri); request.setHeader("x-api-key", "{subscription key}");
// Request body StringEntity reqEntity = new StringEntity("{body}"); request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity();
if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } catch (Exception e) { System.out.println(e.getMessage()); } }}
JavaScript code
<!DOCTYPE html><html><head> <title>JSSample</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script></head><body>
<script type="text/javascript"> $(function() { var params = { // Request parameters "zone_key": "{string}", "as_csv": "{boolean}", }; $.ajax({ url: "https://wprice.io/api/v1/present/generation/production?" + $.param(params), beforeSend: function(xhrObj){ // Request headers xhrObj.setRequestHeader("x-api-key","{subscription key}"); }, type: "GET", // Request body data: "{body}", }) .done(function(data) { alert("success"); }) .fail(function() { alert("error"); }); });</script></body></html>
Node wattpricer.js code
const axios = require("axios");const BASE_URL = `https://wprice.io`
module.exports = { getProdTotal: (zoneKeyString, asCSVBool) => axios({ method:"GET", url : BASE_URL + `/api/v1/present/generation/production?`, headers: { "content-type": "application/json", "x-api-key": "{subscription key}" }, params: { zone_key: zoneKeyString, node_key: nodeKeyString, as_csv: asCSVBool } })}
Node app.js code
const WattPricerAPI = require('./wattpricer')const asyncApiCall = async () => { const response = await WattPricerAPI.getProdTotal('{string}', '{boolean}') console.log(response.data)}asyncApiCall()
Objective C code
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]){ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString* path = @"https://wprice.io/api/v1/present/generation/production"; NSArray* array = @[ // Request parameters @"zone_key={string}", @"as_csv={boolean}", ]; NSString* string = [array componentsJoinedByString:@"&"]; path = [path stringByAppendingFormat:@"?%@", string];
NSLog(@"%@", path);
NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]]; [_request setHTTPMethod:@"GET"]; // Request headers [_request setValue:@"{subscription key}" forHTTPHeaderField:@"x-api-key"]; // Request body [_request setHTTPBody:[@"{body}" dataUsingEncoding:NSUTF8StringEncoding]]; NSURLResponse *response = nil; NSError *error = nil; NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
if (nil != error) { NSLog(@"Error: %@", error); } else { NSError* error = nil; NSMutableDictionary* json = nil; NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding]; NSLog(@"%@", dataString); if (nil != _connectionData) { json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error]; } if (error || !json) { NSLog(@"Could not parse loaded json with error:%@", error); } NSLog(@"%@", json); _connectionData = nil; } [pool drain];
return 0;}
PHP code
<?php// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://wprice.io/api/v1/present/generation/production');$url = $request->getUrl();
$headers = array( // Request headers 'x-api-key' => '{subscription key}',);
$request->setHeader($headers);
$parameters = array( // Request parameters 'zone_key' => '{string}', 'as_csv' => '{boolean}',);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_GET);
// Request body$request->setBody("{body}");
try{ $response = $request->send(); echo $response->getBody();}catch (HttpException $ex){ echo $ex;}
?>
Python 3.X code
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = { # Request headers 'x-api-key': '{subscription key}',}
params = urllib.parse.urlencode({ # Request parameters 'zone_key': '{string}', 'as_csv': '{boolean}',})
try: conn = http.client.HTTPSConnection('wprice.io') conn.request("GET", "/api/v1/present/generation/production?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() print(data) conn.close()except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror))
Python 2.X reached EOL in 2020. For legacy systems that still use it, you can use the following code:
Python 2.7 code
import httplib, urllib, base64
headers = { # Request headers 'x-api-key': '{subscription key}',}
params = urllib.urlencode({ # Request parameters 'zone_key': '{string}', 'node_key': '{string}', 'as_csv': '{boolean}',})
try: conn = httplib.HTTPSConnection('api.pjm.com') conn.request("GET", "/api/v1/present/generation/production?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() print(data) conn.close()except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror))
R code
#NOTE: if you have problems with ggmap, try to install both ggplot and ggmap from github#devtools::install_github("dkahle/ggmap")#devtools::install_github("hadley/ggplot2")library(ggmap)library(ggplot2)library(dplyr)library(rjson)library(jsonlite)library(RCurl)
# Base URL pathbase_url = "https://wprice.io/api/v1/present/generation/production?"full_url = paste0(base_url, "zone_key={string}", "&{node_key}={string}", "&{as_csv}={boolean}")# encode the URL with characters for each space.full_url <- URLencode(full_url)
# Convert JSON to data framepop_proj_data_df <- fromJSON(getURL(full_url))head(pop_proj_data_df, n = 2)
Ruby code
require 'net/http'
uri = URI('https://wprice.io/api/v1/present/generation/production')
query = URI.encode_www_form({ # Request parameters 'zone_key' => '{string}', 'as_csv' => '{boolean}',})if query.length > 0 if uri.query && uri.query.length > 0 uri.query += '&' + query else uri.query = query endend
request = Net::HTTP::Get.new(uri.request_uri)# Request headersrequest['x-api-key'] = '{subscription key}'# Request bodyrequest.body = "{body}"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| http.request(request)end
puts response.body
Rust code (synchronous)
use error_chain::error_chain;use std::io::Read;use exitfailure::ExitFailure;use reqwest::Url;use serde_derive::{Deserialize, Serialize};use std::env;
error_chain! { foreign_links { Io(std::io::Error); HttpRequest(reqwest::Error); }}
fn main() -> Result<()> { let mut res = reqwest::blocking::get("https://wprice.io/api/v1/present/generation/production?zone_key={string}&node_key={string}&as_csv={boolean}")?; let mut body = String::new(); res.read_to_string(&mut body)?;
println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers()); println!("Body:\n{}", body);
Ok(())}
Rust code (async)
use error_chain::error_chain;use exitfailure::ExitFailure;use reqwest::Url;use serde_derive::{Deserialize, Serialize};use std::env;
error_chain! { foreign_links { Io(std::io::Error); HttpRequest(reqwest::Error); }}
#[tokio::main]async fn main() -> Result<()> { let res = reqwest::get("https://wprice.io/api/v1/present/generation/production?zone_key={string}&node_key={string}&as_csv={boolean}").await?; println!("Status: {}", res.status()); println!("Headers:\n{:#?}", res.headers());
let body = res.text().await?; println!("Body:\n{}", body); Ok(())}
Scala code
//Imports for Dispatchimport dispatch._import Defaults._
object Places {
def main(args: Array[String]) {
//Prepare the request object
//even though its a https . doing a .secure is not required val request = url("https://wprice.io/api/v1/present/generation/production") val requestAsGet = request.GET //not required but lets be explicit
//Set the required parameters val builtRequest = requestAsGet.addQueryParameter("x-api-key", "{subscription key}") .addQueryParameter("zone_key", "{string}") .addQueryParameter("node_key", "{string}") .addQueryParameter("as_csv", "{boolean}")
//Make the request (method is already set above) val content = Http(builtRequest)
//Once the response is available //response completed successfully content onSuccess {
//Request was successful & response was OK case x if x.getStatusCode() == 200 => //Response was OK, read the contents handleJsonOutput(x.getResponseBody) case y => //Step 7 : Response is not OK, read the error println("Failed with status code" + y.getStatusCode()) }
//Request did not complete successfully, read the error content onFailure { case x => println("Failed but"); println(x.getMessage) }
println("ENTER TO EXIT") readLine() }
//CASE CLASSES case class Node(nodeName: String, LMP: Double, MLC: Double, MCC: Double) case class Results(billingUnit: String, currency: String, datetime: String, node: Node, source: String, updated: String, zoneKey: String) case class RootJsonObject(results: List[Results])
//JSON imports import org.json4s.jackson.Serialization import org.json4s.jackson.Serialization.{ read } import org.json4s.NoTypeHints
private def handleJsonOutput(body: String): Unit = { //required to set implicit here for JSON serialization to work properly implicit val formats = Serialization.formats(NoTypeHints)
//read the output as a RootJsonObject instance //the read call does the trick of mapping JSon to the case classes val output = read[RootJsonObject](body) println(s"Total Results: ${output.results.size}")
for (each <- output.results) println(s"${each.name.get} at ${each.vicinity.get}") }}
TypeScript code
async function getProdTotal ( query: object ): Promise<object> { const url = new URL('https://wprice.io/api/v1/present/generation/production'); url.search = new URLSearchParams( query ).toString(); const headers = { "x-api-key": "{subscription key}", "content-type":"application/json", }; const response = await fetch( url.toString(), {headers} ); return await response.json();};const query = { zone_key: "{string}", node_key: "{string}", as_csv: "{boolean}",};(async () => { const data = await getProdTotal( query ); console.log(data)})()
#
Successful Response Samples#
HTTP 200 OKThe above commands yield data such as the following (using zone_key=US-MISO
):
- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "datetime": ["2021-05-18T17:55:00-04:00"], "production": {"coal": [32032], "gas": [18803], "nuclear": [9609], "solar": [80], "unknown": [1700], "wind": [9384] }, "source": "misoenergy.org", "storage": {}, "updated": "2021-05-18T17:55:00-04:00", "zoneKey": "US-MISO"}
response for media types 'application/xml' and 'text/xml'
<?xml version="1.0" encoding="UTF-8"?><root> <datetime type="list"> <item type="str">2021-05-18T17:55:00-04:00</item> </datetime> <production type="dict"> <coal type="list"> <item type="int">32032</item> </coal> <gas type="list"> <item type="int">18803</item> </gas> <nuclear type="list"> <item type="int">9609</item> </nuclear> <solar type="list"> <item type="int">80</item> </solar> <unknown type="list"> <item type="int">1700</item> </unknown> <wind type="list"> <item type="int">9384</item> </wind> </production> <source type="str">misoenergy.org</source> <storage type="dict" /> <updated type="str">2021-05-18T17:55:00-04:00</updated> <zoneKey type="str">US-MISO</zoneKey></root>
response for media types 'text/csv'
,datetime,source,updated,zoneKey,production_coal,production_gas,production_nuclear,production_solar,production_unknown,production_wind0,['2021-05-18T17:55:00-04:00'],misoenergy.org,2021-05-18T17:55:00-04:00,US-MISO,[32032],[18803],[9609],[80],[1700],[9384]
#
Error Response Samples(Click to expand ๐ )
- HTTP 400
- HTTP 404
- HTTP 406
- HTTP 422
- HTTP 451
- HTTP 500
#
HTTP 400 BAD REQUEST- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "code": 400, "message": "BAD REQUEST", "timestamp": "2021-07-13T09:20:33+00:00", "detailedMessage": "The server could not understand the request due to invalid syntax."}
response for media types 'application/xml' and 'text/xml'
?xml version="1.0" encoding="UTF-8"?><root> <code type="int">400</code> <message type="str">BAD REQUEST</message> <timestamp type="str">2021-07-13T09:20:33+00:00</timestamp> <detailedMessage type="str">The server could not understand the request due to invalid syntax.</detailedMessage></root>
response for media types 'text/csv'
,code,message,timestamp,detailedMessage0,400,BAD REQUEST,2021-07-13T09:20:33+00:00,The server could not understand the request due to invalid syntax.
#
HTTP 404 NOT FOUND- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "code": 404, "message": "NOT FOUND", "timestamp": "2021-07-13T09:20:33+00:00", "detailedMessage": "The server can not find the requested resource. The endpoint is valid but the resource itself does not exist."}
response for media types 'application/xml' and 'text/xml'
<?xml version="1.0" encoding="UTF-8"?><root> <code type="int">404</code> <message type="str">NOT FOUND</message> <timestamp type="str">2021-07-13T09:20:33+00:00</timestamp> <detailedMessage type="str">The server can not find the requested resource. The endpoint is valid but the resource itself does not exist.</detailedMessage></root>
response for media types 'text/csv'
,code,message,timestamp,detailedMessage0,404,NOT FOUND,2021-07-13T09:20:33+00:00,The server can not find the requested resource. The endpoint is valid but the resource itself does not exist.
#
HTTP 406 NOT ACCEPTABLE- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "code": 406, "message": "NOT ACCEPTABLE", "timestamp": "2021-07-13T09:20:33+00:00", "detailedMessage": "The server, after performing server-driven content negotiation, didn't find any content that conforms to the criteria given by the user agent."}
response for media types 'application/xml' and 'text/xml'
<?xml version="1.0" encoding="UTF-8"?><root> <code type="int">406</code> <message type="str">NOT ACCEPTABLE</message> <timestamp type="str">2021-07-13T09:20:33+00:00</timestamp> <detailedMessage type="str">The server, after performing server-driven content negotiation, didn't find any content that conforms to the criteria given by the user agent.</detailedMessage></root>
response for media types 'text/csv'
,code,message,timestamp,detailedMessage0,406,NOT ACCEPTABLE,2021-07-13T09:20:33+00:00,"The server, after performing server-driven content negotiation, didn't find any content that conforms to the criteria given by the user agent."
#
HTTP 422 UNPROCESSABLE ENTITY- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "code": 422, "message": "UNPROCESSABLE ENTITY", "timestamp": "2021-07-13T09:20:33+00:00", "detailedMessage": "The request was well-formed but was unable to be followed due to semantic errors."}
response for media types 'application/xml' and 'text/xml'
<?xml version="1.0" encoding="UTF-8"?><root> <code type="int">422</code> <message type="str">UNPROCESSABLE ENTITY</message> <timestamp type="str">2021-07-13T09:20:33+00:00</timestamp> <detailedMessage type="str">The request was well-formed but was unable to be followed due to semantic errors.</detailedMessage></root>
response for media types 'text/csv'
,code,message,timestamp,detailedMessage0,422,UNPROCESSABLE ENTITY,2021-07-13T09:20:33+00:00,The request was well-formed but was unable to be followed due to semantic errors.
#
HTTP 451 UNAVAILABLE FOR LEGAL REASONS- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "code": 451, "message": "UNAVAILABLE FOR LEGAL REASONS", "timestamp": "2021-07-13T09:20:33+00:00", "detailedMessage": "The user-agent requested a resource that cannot legally be provided."}
response for media types 'application/xml' and 'text/xml'
<?xml version="1.0" encoding="UTF-8"?><root> <code type="int">451</code> <message type="str">UNAVAILABLE FOR LEGAL REASONS</message> <timestamp type="str">2021-07-13T09:20:33+00:00</timestamp> <detailedMessage type="str">The user-agent requested a resource that cannot legally be provided.</detailedMessage></root>
response for media types 'text/csv'
,code,message,timestamp,detailedMessage0,451,UNAVAILABLE FOR LEGAL REASONS,2021-07-13T09:20:33+00:00,The user-agent requested a resource that cannot legally be provided.
#
HTTP 500 INTERNAL SERVER ERROR- JSON
- XML
- CSV
response for media types 'application/json' and 'text/json'
{ "code": 500, "message": "INTERNAL SERVER ERROR", "timestamp": "2021-07-13T09:20:33+00:00", "detailedMessage": "The server has encountered a situation it doesn't know how to handle."}
response for media types 'application/xml' and 'text/xml'
<?xml version="1.0" encoding="UTF-8"?><root> <code type="int">500</code> <message type="str">INTERNAL SERVER ERROR</message> <timestamp type="str">2021-07-13T09:20:33+00:00</timestamp> <detailedMessage type="str">The server has encountered a situation it doesn't know how to handle.</detailedMessage></root>
response for media types 'text/csv'
,code,message,timestamp,detailedMessage0,500,INTERNAL SERVER ERROR,2021-07-13T09:20:33+00:00,The server has encountered a situation it doesn't know how to handle.