Listening to a websocket stream can be very simple, but unlike Weather API it is not as easy as typing a formatted URL into a browser. Here we have collected some very bare code examples you can use to get started with listening to WebSockets in your applications.
Javascript
Javascript (and NodeJS) is a popular, native language for working with WebSockets in a browser or server environment. The WebSocket object/class is a native part of the language, and creates a very simple interface for receiving WebSocket Messages. Learn More
var my_token = "Your API Token";
var stream_server = "wss://push.synopticdata.com/feed/";
var query_arguments = "units=english&stid=KIAD,KDCA&vars=air_temp,relative_humidity";
// first you should define a function that is called every time a message is received
function message_received(message_event) {
// this function will be called every time there is a new message. And
// the message will be given to the function as a special object.
// First you should extract the JSON object from the message
var message_json = JSON.parse(message_event.data);
// and now you can process your streamed data. Use the `type` key to
// determine what kind of message it is
if (message_json.type == "auth") {
// auth messages contain your session ID, which you can use to
// reconnect where you left off if you have network trouble
} else if (message_json.type == "data") {
// this message contains a list of observations
var ob_index;
for (ob_index in message_json.data) {
//... handle your new observations
}
} else if (message_json.type == "metadata") {
// this is metadata!
}
}
// we had to define that function first, but now we can connect to the socket
// and set that function to be what is called when a message is received.
// and create the socket - this connects and starts listening almost immediately.
var socket = new WebSocket(stream_server+my_token+"/?"+query_arguments);
socket.onmessage = new_message;
WSCat
This is a terminal utility built on NodeJS, that you can use to direclty watch a websocket from a command line. When specifying a URL with parameters in the command line, remember to enclose the URL in quotes. Learn about wscat.
wscat -c "wss://push.synopticdata.com/feed/{Your Token}/?{Arguments}"
Python
There are a number of Python implementations of websockets, and they all work largely the same. This quick example uses websocket-client (pip install websocket-client), but others, including Tornado have the feature built-in.
import json
import random
import time
from websocket import WebSocketException, create_connection
my_token = "Your API Token"
stream_server = "wss://push.synopticdata.com/feed/"
query_arguments = "units=english&stid=KIAD,KDCA&vars=air_temp,relative_humidity"
# Kept across reconnects. Hand it back when you reconnect and the server
# resends what you missed while you were away, instead of starting at "now".
session_id = None
# Seconds to wait before reconnecting, doubling each consecutive failure.
retry_delay = 1
MAX_RETRY_DELAY = 60
# Refusals that will not fix themselves
FATAL = {"invalid_token", "push_not_permitted", "invalid_params", "no_data_available"}
while True:
ws = None
try:
if session_id is None:
path = my_token
else:
# With a session id, connect to /feed/<token>/<session_id> to resume.
path = f"{my_token}/{session_id}"
ws = create_connection(f"{stream_server}{path}/?{query_arguments}")
# The first message is always the auth frame. It says whether you were
# accepted, and carries the session id to reconnect with.
auth = json.loads(ws.recv())
if auth.get("code") != "success":
print("Refused:", auth.get("status"), auth.get("messages"))
if auth.get("status") in FATAL:
break
raise WebSocketException("refused") # transient, so back off and retry
print("Connected: ", auth)
session_id = auth.get("session")
retry_delay = 1
while True:
data = ws.recv()
json_data = json.loads(data)
# and now do things with your received data, before going back to
# the socket for another message.
except (WebSocketException, OSError) as err:
print("Disconnected:", err)
finally:
if ws is not None:
ws.close()
time.sleep(retry_delay + random.uniform(0, 1))
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
You can learn more about websocket-client here. Learn about tornado.websocket here.