Add WeatherSTEM data to your web pages and applications using its Application Programming Interface.

The API is easy to use. You just need knowledge of:

We have a lesson about using the API in our curriculum repository.

You also need an API key which you get automatically when you register with WeatherSTEM.

The WeatherSTEM API Endpoint

All calls to the WeatherSTEM API are made to: https://.weatherstem.com/api

Calling the API

Your API call can be made in any language and will include a JSON object communicating the data you want.

The call can be made via HTTP POST or GET (and JSONP is supported).

API calls can retrieve either current or historical data.

To make a call for data to the WeatherSTEM API, you have to send a request in the form of a JSON object.

The JSON object is passed as a String to the WeatherSTEM API in one of three ways:

  1. As the message body of an HTTP POST
  2. As a parameter named input of an HTTP POST
  3. As a URI-encoded parameter named input of an HTTP GET (include a parameter named callback for JSONP)

Example JSON string for current data

{ 
	"api_key" : "### your API key ###" , 
	"stations" : [""]
}

Example JSON string for historic data (single point)

{ 
	"api_key" : "### your API key ###" , 
	"stations" : [""],
	"at" : "2014-05-08 10:00:00"
}

Example JSON string for historic data (range)

{ 
	"api_key" : "### your API key ###" , 
	"stations" : [ "" ],
	"from" : "2014-05-08 10:00:00",
	"to" : "2014-05-08 10:10:00",
	"sensors" : [ "Thermometer" , "Hygrometer" , "Anemometer" ],
}

Notes

  • The items in the stations array are the handles of the stations whose data you want to pull. (Click here to show a list of stations for .weatherstem.com and their handles)
  • In a historical lookup, if you omit the to property, the current date and time will be used.
  • Click here to show the list of supported sensors

Calls to the API return a JSON structure.

Example current data

The call
{
	"api_key" : "### your API key ###" , 
	"stations" : [""]
}
The response


Example historic data

The call
{
	"api_key" : "### your API key ###" , 
	"stations" : [""],
	"from" : "2014-04-01 18:00:00",
	"to" : "2014-04-01 18:20:00",
	"sensors" : ["Thermometer","Hygrometer","Anemometer"]	
}
The response


ActionScript 3

package {

	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import JSON;
	
	public class WeatherSTEM {
	
		public function WeatherSTEM() {
			var obj:Object = { api_key : "### your API key ###", stations : [""] };
			var jsonString:String = JSON.stringify(obj);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,handler);
			var request:URLRequest = new URLRequest("//.weatherstem.com/api");
			request.method = URLRequestMethod.POST;
			var vars:URLVariables = new URLVariables();
			vars.input = jsonString;
			request.data = vars;
			loader.load(request);
		}
		
		private function handler(event:Event):void {	
			var loader:URLLoader = URLLoader(event.target);
			var jsonString:String = loader.data as String;
			var obj = JSON.parse(jsonString);
		}
		
	}
}

Curl

 curl -X POST https://leon.weatherstem.com/api \
      --data-urlencode 'input={"api_key":"### your API key ###","stations":[""]}'

C#

using System.Net.Http;

using (var client = new HttpClient())
{
    var values = new List<KeyValuePair<string, string>>();
    values.Add(new KeyValuePair<string, string>("input", "{'stations':[''],'api_key':'### your API key ###'}"));

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("https://.weatherstem.com/api", content);

    var responseString = await response.Content.ReadAsStringAsync();
}

Go

package main
 
import
(
	"net/http"
	"strings"
	"io/ioutil"
	"fmt"
	"crypto/tls"
)
 
func main() {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify : true},
	}
	client := &http.Client{Transport: tr}
	apiUrl := "https://.weatherstem.com/api"
	vars := (`{"api_key":"### your API key ###","stations":[""]}`)
	b := strings.NewReader(vars)
	resp, err := client.Post(apiUrl, "application/json", b)
	if err != nil {
	fmt.Println(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Printf("%s\n", string(body))
}

Java

package com.weatherstem;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
import javax.net.ssl.HttpsURLConnection;
 
public class WeatherSTEM {
 
	private final String USER_AGENT = "Mozilla/5.0";
 
	public static void main(String[] args) throws Exception {
 
		WeatherSTEM http = new WeatherSTEM();
		http.sendPost();
 
	}
 
	// HTTP POST request
	private void sendPost() throws Exception {
 
		String url = "https://.weatherstem.com/api";
		URL obj = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
 
		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
 
 		String urlParameters = "input={api_key:'### your API key ###',stations:['']}";
 
		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		wr.flush();
		wr.close();
 
		int responseCode = con.getResponseCode();
 
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
 
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
 
		//print result
		System.out.println(response.toString());
 
	}
 
}

JQuery

$.ajax({
	type: "POST",
	url: "//" +  + ".weatherstem.com/api",
	data: JSON.stringify({ api_key : "### your API key ###", stations : [""] }),
	dataType: "json",
	success: function(responseData, textStatus, jqXHR) {
		if (responseData.error) {
			return alert('An error was encountered: ' + responseData.error);
		}
		alert(JSON.stringify(responseData));
	},
	error: function(responseData, textStatus, errorThrown) {
		alert(responseData + ':' + errorThrown);
	}
});

JSONP

<html>
	<head>
		<title>JSONP Example</title>
		
		<!-- input param is a URI escaped JSON string -->
		<script src="//.weatherstem.com/api?input=%7B%22stations%22%3A%5B%22%22%5D%2C%22api_key%22%3A%22### your API key ###%22%7D&callback=myCallback"></script>
		<script>
			function myCallback(data) {
				var objString = unescape(data);
				alert(objString);
			}
		</script>
	</head>
	<body>
	</body>
</html>

Objective C

// send the request.  Your class must be a NSURLConnectionDelegate

-(void)getWeatherStemData
{
    // json data...
    
    NSData* postData= [@"{\"api_key\": \"### your API key ###\",\"stations\": [\"\"]}" dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *tString = @"https://.weatherstem.com/api";
    NSURL* url = [NSURL URLWithString:tString];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                                  delegate:self];
    
    [connection start];
}

// initialize the buffer
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _responseData = [[NSMutableData alloc] init];
    
}

// fill the buffer
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    [_responseData appendData:data];
}

// put the result in a dictionary and send it to the console
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
   
    NSError *localError = nil;
    NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:&localError];
    NSLog( @"%@", parsedObject );

}

Perl

#!/usr/bin/perl

use strict;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
my $ua = LWP::UserAgent->new();
my $url = 'https://.weatherstem.com/api';

my $vars = { input => '{"stations":[""],"api_key":"### your API key ###"}'};

my $req = POST $url, $vars;
my $content = $ua->request($req)->content;

PHP

<?php
 
$url = 'https://.weatherstem.com/api';
$vars = array(
	"stations"    => array(""),
	"api_key"     =>"### your API key ###"
);
  
$options = array(
	'http'    => array(
	'method'    => 'POST',
	'content'   => json_encode( $vars ),
	'header'    =>  "Content-Type: application/json\r\n" .
					"Accept: application/json\r\n"
		)
	);
  
$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
print_r($response);
 
?>

Python

import urllib2,json

url = 'https://.weatherstem.com/api'
indata = {'api_key':'### your API key ###','stations':['']}

request = urllib2.Request(url)
request.add_header('Content-Type','application/json')
outdata = json.dumps(indata)
response = urllib2.urlopen(request,outdata)

print json.load(response)

Ruby

#!/usr/bin/env ruby
 
require 'uri'
require 'json'
require 'net/http'
require 'net/https'
 
uri             = URI.parse("https://.weatherstem.com/api")
https           = Net::HTTP.new(uri.host, uri.port)
https.use_ssl   = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
 
@vars    = {
    "api_key"   => "### your API key ###",
    "stations"  => [""]
}.to_json
 
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' => 'application/json'})
req
.body = @vars
response = https.request(req)
puts "Response #{response.code} #{response.message}: #{response.body}"

Swift

public class WeatherSTEM : NSObject {

	public static func get_data(url:String, params _params:[String:String]?, handler:(String?) -> ()) {
	
		let nsurl:NSURL = NSURL(string : url)!
		let session:NSURLSession = NSURLSession.sharedSession()
		request.HTTPMethod = "POST"
		request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
		
		var params:String = ""
		if let _params = _params {
		
			for(key,value) in _params {
				params += key + "=" + value + "&"
			}
			
			if params != "" {
				params = String(params.characters.dropLast())
			}
		
		}
		
		request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
        
		let task = session.dataTaskWithRequest(request) {
            
			(let data:NSData?, let response:NSURLResponse?, let error:NSError?) in
            
			guard error == nil else {
				handler((error?.localizedDescription)!)
				return
			}
            
			var data_string:NSString = ""
            
			if let data = data {
				data_string = NSString(data: data, encoding: NSUTF8StringEncoding)!
				return handler(data_string as String)
			}
            
            
		}
	    
		task.resume()
	
	}

}

// EXAMPLE CODE TO GET DATA
let json:String = "{'api_key','### your API key ###','stations':['']}"
let params:[String:String] = ["input":json]

WeatherSTEM.get_data("https://.weatherstem.com/api",params:params, handler:{
	(data:String?) -> () in
	print(data)
})

The WeatherSTEM JavaScript component (based on JQuery) is a way to add current data to your page with no programming.

Example

<!DOCTYPE html>
<html>
	<head>
		<title>The temperature</title>
		
		<!-- JQuery is required for the WeatherSTEM component to work -->
		<script src="//code.jquery.com/jquery-latest.min.js"></script>
		
		<!-- WeatherSTEM API component must be included AFTER JQuery include -->
		<script src="//static.weatherstem.com/api.min.js"></script>
		
		<!-- You must include your API key -->
		<meta name="WeatherSTEM-api-key" content="### your API key ###"/>
		
		<!-- This sets the station scope for the page -->
		<meta name="WeatherSTEM-station" content="/"/>
		
	</head>
	<body>
	
		<!-- data-sensor can be the value of any supported sensor -->
		The current temperature is <span data-sensor="Thermometer"></span>° F.
		
	</body>
</html>

Notes

  • You can download the source of the component and modify it at will.
  • The station scope set in the META tag is of the form domain handle/station handle, for example, /.
  • The station scope can also be set to random which pulls data from a random a station in the WeatherSTEM network, closest which pulls data from the station closest to the user in the WeatherSTEM network, and assigned which will look for a cookie named station and use it as the station to pull data from
  • The component includes a public WeatherSTEM.get() method which accepts a handler function as input and will return to it the latest data from the station in scope.
  • The component also includes a public WeatherSTEM.update() method which updates the data from the station in scope. By default, this method is called every 60 seconds but you can call it manually anytime.
  • Any element with a data-sensor attribute will have its child contents replaced by the current reading from the specified sensor. Values can be implemented for dynamically added elements by calling WeatherSTEM.update().