Terra
Integrations
Research

Integration

API
Unified API
SDK
SDK
Authentication
Authentication
Streaming
Streaming
Blood
Blood Report API
Planned Workouts
Planned Workouts
AI Interface
AI Interface

User engagement

Graph API
Graph API
Scores
Health Scores
Rewards
Health Rewards

Use cases

Enterprise
Enterprise
Insurance
Insurance

Developers

Wearable Data
Wearable Data
Community
Community
Documentation
Documentation

Learn

Blog
Blog
Podcast
Podcast
Events
Events
Reports
Reports

Company

Customers
Customers
Careers
Careers
Partners
Partners
Support
Support
Pricing
Become an integrationGet started
IntegrationsResearch
Unified APIUnified APISDKSDKAuthenticationAuthenticationStreamingStreamingGraph APIGraph APIScoresScoresRewardsRewardsBlood Report APIBloodAI InterfaceAI Interface
EnterpriseEnterpriseInsuranceInsuranceWearable DataWearable DataCommunityCommunityDocumentationDocumentationBlogBlogPodcastPodcastEventsEventsReportsReportsCustomersCustomersCareersCareersPartnersPartnersSupportSupport
Pricing
Get startedBecome an integration
next ventures
pioneer fund
samsung next
y combinator
general catalyst

The world's best health apps run on Terra data

Get started
ProductsIntegrations AI Interface Authentication Mobile Development Documentation GraphAPI
DocumentationAPI SDK Quickstart
CommunityBlog Research Community Podcast Github
CompanyAboutCareersCustomersBecome an IntegrationCookies PolicyGDPRPrivacy PolicyTerms of Purchase
© Terra API. 2026 — All rights reserved.

Cookie Preferences

Essential CookiesAlways On
Advertisement Cookies
Analytics Cookies

Crunch Time: Embrace the Cookie Monster Within!

We use cookies to enhance your browsing experience and analyse our traffic. By clicking “Accept All”, you consent to our use of cookies according to our Cookie Policy. You can change your mind any time by visiting out cookie policy.

Cookies Policy
< Blogs
Elliott Yu
Elliott Yu

June 21, 2022

How-Tos: Using WebSockets

Live-streaming data is only a handshake away.

Websockets allow you to maintain a stream of data in real-time whenever you need it! You can use it to build some really amazing features ranging from simple heart rate streaming to your phone during a run to complex robotic hand gestures to the other side of the world so that a robotic hand on the other side mimics your hand gestures.

Definitions

Websocket connections are quite simple in a top-level sense: You initiate a connection with a WebSocket server, and upon connection, you might be asked for verification for connection. This part initiates a handshake with the server. After that, you simply maintain the server connection and start sending/receiving live streaming data!

To maintain the server connection, it is often needed to perform a sort of "connection check" every once in a while. Typically this is done byPING PONG. You ping the server, and the server responds with a pong signifying the connection is still alive.

WebSocket Connection

Example Usage

Each WebSocket server has its own protocol. We here at Terra created a very simple WebSocket server to stream data from a user's device to our developers.

Let's assume you are a developer using Terra. You wish to connect to our WebSocket server to see real-time data from your users.

There are a few things we must do:

  • Initiate the connection
  • Send a verification (we use tokens)
  • Maintain a heartbeat (The ping/pong we use to keep the connection in check)

For this example, we will be using Javascript's ‘ws' library. However, implementation is similar for other languages!

Let us also assume you have generated the token. If you do not know how to please check out our blog on how to use a REST API!

First, let us maintain the connection and perform the handshake:

The code above initializes a function for keeping a WebSocket connection. On line 6 it initiates a connection to the WebSocket server.

The ‘ws' library allows us to implement EventListener's through the addEventListener function.

  • open tells the connection what should happen upon connection. Right now we simply print Connection Established
  • close and error currently also only prints that the connection either closed or errored. On close, there's usually a reason why it closed, and on error, there usually is an error code telling you what was the cause.
  • message is the main part. You can do something on a message sent to you. Terra's websocket messages always come with an op field signifying an Opcode. Opcode 2 is "HELLO". Upon initialising a connection, this sends you a payload as such: {"op":2, "d":{"heartbeat_interval": 40000}}. This message essentially tells you to send a ping (in this case a heart beat), every 40000 milliseconds. This is what the heartBeat() function does. The setInterval() function allows you to periodically call the function at a set interval. Opcode 1 means "Heartbeat acknowledged". This means that the server knows you are still connected and would not close your connection. Finally, Opcode 3 means "VERIFY". You send this payload to the server to verify your status.
  • Any other messages, are simply printed.

Next, we can run the function, and see what happens:

Connection Established
↓  {"op":2,"d":{"heartbeat_interval":40000}}
↑  {"op":0}
↑  {"op":3,"d":{"token":"dGVzdGluZ0VsbGlvdHQ.MU1fASa1nR9EpQWQx67xIN7veTFKFwudaB4HbN4kw9A","type":1}}
↓  {"op":1}
↓  {"op":4}
↑  {"op":0}
↓  {"op":1}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:08.055Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12254,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:08.701Z","val":87.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12255,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:09.698Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12256,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:11.041Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12257,"t":"HEART_RATE"}
↓  {"op":5,"d":{"ts":"2022-06-01T14:47:12.049Z","val":86.0},"uid":"100b370c-d2be-42a2-b757-01fc85c41031","seq":12258,"t":"HEART_RATE"}

We can break the messages down:

  • An initial Hello from the server with Opcode 2 followed by the script sending an Opcode 3 with the verification payload. The server then sends back an Opcode 4 meaning "READY".
  • The 'Opcode 0 and Opcode 1 to and from the server is simply the heart beating
  • Then there are many Opcode 5 messages that contain data for a user with uid and their "HEART_RATE" values.

Go wild

The messages in these WebSocket connections can be completely arbitrary. As said before, each WebSocket server has its own protocol and may not adhere to the same one. However, the idea is always the same: you initiate the connection, complete the handshake, and do something "on message, on open, and on close". These are usually implemented within an external library that you can use. Similar to the "ws" library from javascript, there's also "websockets" library on python, URLSessionWebSocketTask object in swift, and "okhttp3" on java to create WebSocket connections.

Keeping this same structure in mind, you should be able to connect to any WebSocket server as you wish (as long as you follow their structure). Other than the current example given, you can also send messages through WebSockets in a chat room, get live social media feeds, get real-time financial stock data, or even real-time sports updates!

Related Articles

The complete guide: How the new Google Health API works

May 18, 2026

The complete guide: How the new Google Health API works

Google Health API replaces the Fitbit Web API. This is the field guide with code, schemas, and a migration playbook to help you understand where Google Health is heading.

Vanessa Neeff
5 Lessons for Standing Out at HLTH

December 5, 2024

5 Lessons for Standing Out at HLTH

5 lessons from team Terra API for making a lasting impact at HLTH: from engaging senses to building real touch points, here’s what we learned from the HLTH event.

Vanessa Neeff
Strava Pulls the Plug on their API: What This Means for Developers

November 21, 2024

Strava Pulls the Plug on their API: What This Means for Developers

Strava discontinued their API service, changing the ecosystem of third-party apps that have relied on their platform. How can developers react to this?

Terra APITerra API

More Topics

All Blogs
Team Spotlight
Startup Spotlight
How To
Blog
Podcast
Product Updates
Wearables
See All >
The complete guide: How the new Google Health API works

The complete guide: How the new Google Health API works

Google Health API replaces the Fitbit Web API. This is the field guide with code, schemas, and a migration playbook to help you understand where Google Health is heading.

Vanessa NeeffVanessa Neeff
May 18, 2026
September 2025 updates

September 2025 updates

July: Terra Research launches, Lab Reports land in the dashboard with PDF/Image → JSON, and Samsung Health moves to the new Data SDK for a tighter Android integration. 🚀

Alex VenetidisAlex Venetidis
October 1, 2025
August 2025 updates

August 2025 updates

🎉 July Highlights: InBody Goes Global, Faster APIs, and Rock-Solid Data 💪📊

Alex VenetidisAlex Venetidis
September 1, 2025
July 2025 updates

July 2025 updates

July = rock-solid Terra: WHOOP V2, Garmin & Fitbit bug fixes, faster SDKs, plus bulk blood-report uploads with smarter reference ranges. Reliability + data power-ups! 💪🩸

Alex VenetidisAlex Venetidis
August 2, 2025
June 2025 Updates

June 2025 Updates

June brings Terra MCPs for AI-driven setup, Fern-powered Python/JS SDKs with strong typing, and official Expo plugin support—build faster with less friction. 🚀🧰📱

Alex VenetidisAlex Venetidis
July 1, 2025