Degree Days

Degree Days

Weather Data for Energy Professionals

Access the Degree Days.net API using PHP

This page has some sample code showing how to use PHP to specify a JSON request, send it to our API servers (past the security system), and process the JSON response that comes back.

It's not a full client library (like we have for Java, .NET, and Python), but, thanks to PHP's excellent support for JSON, it should be pretty easy to adapt it to suit your needs.

See the JSON API docs for more about specifying the data you want in the JSON request. There are lots of options, and the request included in the PHP code below is just a simple example. The JSON docs also explain more about the data you can expect back in the response.

You might also find the JSON API test tool useful for testing different JSON requests and seeing the JSON responses that come back.

<?php

// The test API access keys are described at www.degreedays.net/api/test
// They will let you access data from the Cape Cod area only.
// To fetch data from locations worldwide, sign up for a proper API account at
// www.degreedays.net/api/ and copy your API access keys here.
$accountKey = 'test-test-test';
$securityKey = 'test-test-test-test-test-test-test-test-test-test-test-test-test';
// You can call the API over HTTP using http://apiv1.degreedays.net/json or
// over HTTPS using https://apiv1.degreedays.net/json - set the endpoint URL
// below as appropriate.
$endpoint = 'http://apiv1.degreedays.net/json';



// ************* STEP 1: Create the request ************************************
// First we create a JSON request that specifies what we want from the API.
// See www.degreedays.net/api/json#request for more on this.

// You can fetch data from a station ID, a longitude/latitude position, or a 
// postal/zip code.
$location = [
    'type' => 'PostalCodeLocation',
    'postalCode' => '02532',
    'countryCode' => 'US'
];
// In this example we fetch both HDD and CDD, using the same breakdown (daily
// data covering the last 7 days) for both. For more breakdown options see:
// www.degreedays.net/api/json#breakdown
$breakdown = [
    'type' => 'DailyBreakdown',
    'period' => [
        'type' => 'LatestValuesPeriod',
        'numberOfValues' => 7
    ]
];
$locationDataRequest = [
    'type' => 'LocationDataRequest',
    'location' => $location,
    'dataSpecs' => [
        // Here we specify 2 DataSpec items: one for HDD and one for CDD.  You
        // can specify up to 100 DataSpec items in one request (e.g. to fetch
        // data in lots of base temperatures).  Give each DataSpec a unique name
        // so you can get the corresponding DataSet from the response.
        'myHDD' => [
            'type' => 'DatedDataSpec',
            'calculation' => [
                'type' => 'HeatingDegreeDaysCalculation',
                'baseTemperature' => [
                    'unit' => 'F',
                    'value' => 60
                ]
            ],
            'breakdown' => $breakdown
        ],
        'myCDD' => [
            'type' => 'DatedDataSpec',
            'calculation' => [
                'type' => 'CoolingDegreeDaysCalculation',
                'baseTemperature' => [
                    'unit' => 'F',
                    'value' => 70
                ]
            ],
            'breakdown' => $breakdown
        ]
    ]
];
$fullRequest = [
    'securityInfo' => [
        'endpoint' => $endpoint,
        'accountKey' => $accountKey,
        'timestamp' => gmdate('c'),
        'random' => uniqid()
    ],
    'request' => $locationDataRequest
];
$fullRequestJson = json_encode($fullRequest);
// Now our JSON request is ready.  Uncomment the line below to see the JSON:
// header('Content-type: application/json'); echo $fullRequestJson; exit;



// ************* STEP 2: Send the request to the API ***************************
// Next we sign the JSON request and package everything together into an HTTP
// request which we send to the Degree Days.net API.  This follows the spec at
// www.degreedays.net/api/json#send (though you can just copy/paste).
$signatureBytes = hash_hmac('sha256', $fullRequestJson, $securityKey, true);
// The API requires the JSON request and the signature to be base64url encoded.
function base64url_encode($unencoded) { 
    return rtrim(strtr(base64_encode($unencoded), '+/', '-_'), '='); 
}
// Prepare the HTTP request parameters to send to the API servers:
$requestParameters = [
    'request_encoding' => 'base64url',
    'signature_method' => 'HmacSHA256',
    'signature_encoding' => 'base64url',
    'encoded_request' => base64url_encode($fullRequestJson),
    'encoded_signature' => base64url_encode($signatureBytes)
];
// Send the HTTP request to the API servers using PHP's cURL library:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestParameters));
if (defined('CURLOPT_ENCODING')) {
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$fullResponseJson = curl_exec($ch);
curl_close($ch);



// ************* STEP 3: Process the response from the API *********************
// The JSON response is explained at www.degreedays.net/api/json#response

// Uncomment the line below to see the JSON response:
// header('Content-type: application/json'); echo $fullResponseJson; exit;

// Use json_decode to turn the JSON response into a PHP object:
$fullResponse = json_decode($fullResponseJson);
// $fullResponse->metadata has some rate limit info, but we are mainly
// interested in $fullResponse->response (a LocationDataResponse in this case).
$response = $fullResponse->response;
if ($response->type === 'Failure') {
    // See www.degreedays.net/api/json#failure for more about failures.
    echo 'Request failure: ' . print_r($response, true);
} else {
    // The response contains a lot of useful info.  See above to view the JSON,
    // or check the JSON docs at www.degreedays.net/api/json#response
    echo 'Station ID: ' . $response->stationId . '<br/>';
    // "myHDD" is the name we gave the HDD DataSpec in our request.
    $hddData = $response->dataSets->myHDD;
    if ($hddData->type === 'Failure') {
        echo 'Failure for HDD DataSet: ' . print_r($hddData, true);
    } else {
        echo '<br/>HDD:<br/>';
        foreach ($hddData->values as $v) {
            echo $v->d . ': ' . $v->v . '<br/>';
        }
    }
    $cddData = $response->dataSets->myCDD;
    if ($cddData->type === 'Failure') {
        echo 'Failure for CDD DataSet: ' . print_r($cddData, true);
    } else {
        echo '<br/>CDD:<br/>';
        foreach ($cddData->values as $v) {
            echo $v->d . ': ' . $v->v . '<br/>';
        }
    }
}

?>

Hopefully the example code above, the JSON API docs, and the JSON API test tool will be enough to get you going, but please feel free to email us if you'd like more help.

It is also worth reading the higher-level integration guide for tips on the various approaches to integrating with the API. We have helped a lot of businesses integrate their software with our API so we are very familiar with the patterns that work well for common use cases.

Choose your Plan and Sign Up Today!

© 2019 BizEE Software - About | Contact | Privacy | Web Tool | API | Integration Guide | API FAQ | API Sign-Up