Persistent Connections (WebSocket)
Real-time API Calls with WebSocket
Persistent connections such as WebSocket are essential for real-time streaming and long-running tasks. Unlike traditional REST API calls, WebSockets allow continuous data exchange between the client and server without the need for repeated requests. In Fiscus SDK, WebSocket connections provide a streamlined way to handle real-time data streams across various APIs, now with added support for stopping and restarting streams through the client class directly.
When to Use WebSocket Connections
- Real-time data streaming: For use cases like stock ticker updates, chat messages, or IoT data streams.
- Long-running tasks: Tasks that take time to complete, requiring updates throughout execution.
- Event-driven architectures: When actions on the server-side trigger updates to the client in real-time.
FiscusConnectionType Enum
To enable WebSocket connections, the Fiscus SDK provides a specific connection type via the FiscusConnectionType
enum. This allows you to choose between REST and WebSocket for each API operation.
FiscusConnectionType.REST
: Used for traditional request-response API calls.FiscusConnectionType.WEBSOCKET
: Used for persistent, real-time connections.
Setting Up WebSocket Connections
You can specify WebSocket as the connection type when executing an operation. With the recent SDK updates, you can also easily stop and restart the WebSocket stream directly from the FiscusClient
class.
- Python
Example: Subscribing to Real-Time Stock Ticker Data
This example demonstrates how to set up a WebSocket connection to subscribe to real-time stock ticker updates and how to handle the stream lifecycle.
from fiscus import FiscusClient, FiscusUser, FiscusConnectionType
# Initialize Fiscus client and user
client = FiscusClient(api_key='YOUR_FISCUS_API_KEY')
user = FiscusUser(user_id='user_123', client=client)
# Define the callback to handle real-time data
def on_stream(data):
print(f"Received real-time stock update: {data}")
# Set the callback for streaming data
callbacks = {'fiscus_on_stream': on_stream}
# Execute the operation with WebSocket connection type
response = client.execute(
connector_name='StockAPI',
operation='subscribe_ticker',
params={'ticker': 'AAPL'},
callbacks=callbacks,
connection_type=FiscusConnectionType.WEBSOCKET,
user=user
)
In this setup:
on_stream
: A callback function that processes the streaming data in real-time.connection_type=FiscusConnectionType.WEBSOCKET
: Ensures the operation uses a WebSocket connection instead of a REST request.
Stopping and Restarting the WebSocket Stream
The SDK update allows you to easily stop or restart a WebSocket stream via methods provided by the client class.
stop_stream
(): Stops the WebSocket stream.restart_stream
(): Restarts the WebSocket stream.
Example: Stopping and Restarting a WebSocket Stream
# Stop the WebSocket stream
client.stop_stream()
# Restart the WebSocket stream
client.restart_stream()
With these methods:
stop_stream
() halts the WebSocket connection, which is useful for resource management when the stream is no longer needed.restart_stream
() reconnects the WebSocket, resuming data flow for long-running or interrupted tasks.
Handling Streaming Data
The Fiscus SDK allows you to manage incoming streaming data using the fiscus_on_stream
callback. This callback ensures that you can process real-time data as it arrives.
Example: Handling Streaming Data in Real-Time
def handle_stream_data(data):
print(f"Processing data: {data}")
callbacks = {'fiscus_on_stream': handle_stream_data}
# Execute WebSocket-based operation
response = client.execute(
connector_name='StockAPI',
operation='subscribe_ticker',
params={'ticker': 'AAPL'},
callbacks=callbacks,
connection_type=FiscusConnectionType.WEBSOCKET,
user=user
)
In this example:
handle_stream_data
: Processes incoming data in real-time as it’s received through the WebSocket connection.
Managing Persistent Streaming Data
For persistent WebSocket connections, it's important to manage their lifecycle effectively, especially for long-running streams. This includes stopping and restarting the connection as needed, which is now simplified in the SDK.
Graceful Disconnection and Reconnection
You can now easily stop and restart the WebSocket stream using the methods provided by the client class.
Example: Managing the WebSocket Stream Lifecycle
# Start the WebSocket stream
client.execute(
connector_name='StockAPI',
operation='subscribe_ticker',
params={'ticker': 'AAPL'},
callbacks=callbacks,
connection_type=FiscusConnectionType.WEBSOCKET,
user=user
)
# Stop the stream when it's no longer needed
client.stop_stream()
# Restart the stream if necessary
client.restart_stream()
Best Practices for Managing WebSocket Connections
- Use Callbacks Efficiently: Always define callback functions for both streaming and error handling.
- Gracefully Handle Disconnections: Stop the stream when no longer needed using the
stop_stream
() method. - Monitor the Stream: Continuously monitor the stream for any interruptions and handle reconnections with
restart_stream
(). - Re-authenticate if Needed: For long-running WebSocket sessions, tokens may expire. Use the
fiscus_on_auth
callback to handle re-authentication if required.
Conclusion
- Real-time Streaming: WebSocket connections are ideal for real-time data, such as stock updates, live events, or IoT data streams.
- Easy Stream Management: The updated Fiscus SDK makes it easier to manage WebSocket streams with stop and restart methods directly from the client class.
- Seamless Integration: The SDK provides a simple interface for managing persistent connections and streaming data.
With these enhancements, the Fiscus SDK empowers developers to create real-time, event-driven applications with minimal friction.