Using the API
To interact with our WebSocket API, establishing a connection to the WebSocket server is the first step. This connection is initiated by connecting to our WebSocket endpoint using the WSS protocol, which ensures that the data exchanged between the client and server is encrypted and secure.
Estabilishing a connection
- Use a WebSocket client to connect to the server at
wss://api.emogg.com/ws/v1.
Remember that wss protocol uses port 443 for connections. Some clients do not set this value automatically.
- Authenticate the connection, see Authenticating.
If your first request is other than an authentication message the connection will be terminated by the server inmediatly.
- Once authenticated, you can start sending requests over this persistent connection.
Server will disconnect you automatically after 65 seconds of inactivity. To ensure the long-lived connections see Heartbeats.
Examples
- JavaScript
- Python
// Create a new WebSocket connection with the API
const ws = new WebSocket('wss://api.emogg.com/ws/v1');
// Listen for open event, which fires when the connection is estabilished
ws.onopen = function() {
const authMessage = {
"id": 1,
"path": "auth:token",
"body": {
"token": "YOUR_TOKEN" // Replace YOUR_TOKEN with your real authentication token
}
};
// Send the message as a JSON string
ws.send(JSON.stringify(authMessage));
};
ws.onmessage = function(event) {
console.log('Message from server:', event.data);
// For our authentication request, the response would be:
// { "id": null, "path": "auth:token", "status": 200 }
};
// Listen for the 'close' event
ws.onclose = function(event) {
console.log('WebSocket connection closed:', event);
};
# Example using websocket-client: pip install websocket-client
import websocket
import json
def on_open(ws):
print("Connection established")
auth_message = {
"id": 1,
"path": "auth:token",
"body": {
"token": "YOUR_TOKEN" # Replace YOUR_TOKEN with your real authentication token
}
}
# Send the message as a JSON string
ws.send(json.dumps(auth_message))
def on_message(ws, message):
print("Message from server: ", message)
# For our authentication request, the response would be:
# { "id": null, "path": "auth:token", "status": 200 }
def on_close(ws, close_status_code, close_msg):
print("Connection closed")
if __name__ == "__main__":
ws_url = 'wss://api.emogg.com/ws/v1'
# Create a new WebSocket connection
ws = websocket.WebSocketApp(ws_url,
on_open=on_open,
on_message=on_message,
on_close=on_close)
# Connect
ws.run_forever()
Request format
All requests sent over the WebSocket connection must be formatted as JSON objects.
API will close the connection inmediatly if non-valid JSON data is received or the received data fails to match the following structure.
These JSON requests primarily consist of three fields:
| Field | Type | Description | Required |
|---|---|---|---|
| id | number / string | An unique identifier for the request, set by the user. It can be a number or a string of up to 36 characters. This ID will be included in the server's response, allowing the user to correlate a server response with its corresponding request. | No |
| path | string | Specifies the API endpoint being called. | Yes |
| body | object | Contains the specific fields required for the request targeted at the specified path. | No |
Server messages format
Messages received from the WebSocket API can be categorized into the types:
Successful responses
These responses are triggered by a user request. Their structure include the following fields:
| Field | Type | Description |
|---|---|---|
| id | nullable number / string | If specified, the identifier sent in the original request. |
| path | string | The API route that is providing the response. |
| status | number | An HTTP-like status code indicating the result of the request. |
| body | object | If needed, specific fields related to the response from this route. Check each endpoint reference for specific information. |
Example
{
"id": 1,
"path": "auth:token",
"status": 200
}
Error responses
These responses are sent when a user request generates an error. Contain all the same fields as a successful response and also:
| Field | Type | Description |
|---|---|---|
| error | boolean | Boolean field with value true present on every error message |
| data.message | string | Field inside the data object with a string containing detailed information about the error. |
Example
{
"error": true,
"id": 2,
"path": "channels:unsubscribe",
"status": 404,
"data": {
"message": "Subscription not found"
}
}
Event notifications
When you subscribe to a channel, you opt in to receive real-time updates related to that channel. The structure of event messages is designed to easily identify the source (via subscriptionId) and to process the incoming data accordingly.
These message types are arrays with three elements:
[
SUBSCRIPTION_ID,
EVENT_TIMESTAMP,
EVENT_TYPE,
EVENT_DATA
]
| Field | Type | Description |
|---|---|---|
| SUBSCRIPTION_ID | string | The ID of the subscription. |
| EVENT_TIMESTAMP | date | Date in which the event was generated. |
| EVENT_TYPE | string | Type of event. It determines the content of the field EVENT_DATA. |
| EVENT_DATA | array | Information pertaining to the event. Check each channel reference page for specific information. |
Example
// session_emotions_counts channel event
[
"lusik292xia9b1",
1712675148150,
"sec",
[
{ "fatigue": 4, "exaltation": 33, "focus": 21, "seriousness": 11 }
]
]
Hearbeats
Server will close idle connections automatically after 65 seconds of inactivity. This idle timeout is reset every time a message is sent from the API, whether it be in response to a request or due to a new event on a channel to which the user is subscribed.
To keep the WebSocket connection alive even during periods of inactivity you can periodically reset the aforementioned timeout by sending periodic (ideally each 30 seconds) heartbeat signals.
This can be done in two ways:
- WebSocket Ping Frames: Send a
pingframe through the WebSocket protocol. The server will respond with apongframe as soon as possible. - API Ping Endpoint: Alternatively, users can make a call to the
pingendpoint in the WebSocket API. See Ping.
Response status codes
All the responses generated as the result of a user request include an status field with a HTTP-like code indicating the result of the operation. Below is a table of status codes returned by the Emogg WS API and their meanings:
| Code | Title | Description | Closes the connection |
|---|---|---|---|
| 200 | OK | The request has succeeded. The client can read the result of the request in the body if present. | No |
| 400 | Bad Request | The server cannot or will not process the request due to something that is perceived to be a client error (e.g., missing required fields). | No |
| 401 | Unauthorized | The connection is not authenticated or the authentication details provided are not valid. | Yes |
| 404 | Not Found | The requested resource does not exist. | No |
| 405 | Malformed Payload | The received payload do not comply with the request structure specification. | Yes |
| 429 | Too Many Requests | The user has sent too many requests in a given amount of time. | Yes |
| 500 | Internal Server Error | Something went wrong on Emogg's end. (These are rare.) | No |