# Fetch
Source: https://docs.byul.ai/api-reference/endpoint/get
GET /news
Retrieve the latest financial news articles with filtering and pagination support
> This endpoint supports date range filtering via `startDate` and `endDate` (ISO 8601).
# MCP Error Handling
Source: https://docs.byul.ai/mcp/error-handling
Handling MCP communication and proxied Byul API errors
## Common error format
Errors proxied from REST follow the same format as in the REST docs:
```json
{
"statusCode": 401,
"message": "API key is required. Please provide a valid V2 API key in the X-API-Key header.",
"error": "Unauthorized",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
## Frequent issues
* `Missing BYUL_API_KEY environment variable` → set the environment variable before launching
* `Rate limit exceeded` → apply backoff/retry per REST guidance
## Retry guidance
Apply exponential backoff for 429 and 5xx responses. You can reuse the REST examples as-is.
# null
Source: https://docs.byul.ai/mcp/examples/claude-code
title: "Claude Code"
description: "Configure @byul/mcp for the Claude Code VS Code extension"
------------------------------------------------------------------------
## CLI
```bash
claude mcp add -e BYUL_API_KEY=byul_api_key --scope user byul npx -- -y @byul/mcp
```
## Settings JSON
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
# null
Source: https://docs.byul.ai/mcp/examples/claude-desktop
title: "Claude Desktop"
description: "Configure @byul/mcp for Claude Desktop"
-----------------------------------------------------
## Configuration
`claude_desktop_config.json`:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
This package supports stdio (local) transport only. HTTP/SSE transports are not provided.
# null
Source: https://docs.byul.ai/mcp/examples/cursor
title: "Cursor"
description: "Use @byul/mcp inside the Cursor editor"
-----------------------------------------------------
## Configuration file
`~/.cursor/mcp.json`:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
## Usage example
```txt
tools.call name="news_fetch" params={"minImportance":7,"limit":10}
```
# null
Source: https://docs.byul.ai/mcp/examples/gemini-cli
title: "Gemini CLI"
description: "Use @byul/mcp with the Gemini CLI"
------------------------------------------------
## Settings file
Open `~/.gemini/settings.json` and add:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
If the `mcpServers` object is missing, create it.
Only local stdio transport is supported. Remote HTTP/SSE endpoints are not available.
# null
Source: https://docs.byul.ai/mcp/examples/windsurf
title: "Windsurf"
description: "Use @byul/mcp with Windsurf's Cascade assistant"
--------------------------------------------------------------
## Configuration
`windsurf_mcp.json`:
```json
{
"mcpServers": {
"mcp-server-byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
# MCP Introduction
Source: https://docs.byul.ai/mcp/introduction
Overview and architecture of @byul/mcp
## What does it provide?
`@byul/mcp` exposes Byul's REST API through MCP tools and resources over stdio.
* **Tool**: `news_fetch` – proxies `GET /news` (filters and pagination)
* **Resource**: `byul://news{?limit,cursor,sinceId,minImportance,q,symbol,startDate,endDate}`
* **Response format**: summary string + original JSON payload
## Requirements
* Node.js 18+
* `BYUL_API_KEY` environment variable (e.g., `byul_api_key`)
## Architecture
Register `@byul/mcp` in your MCP-compatible client.
The client launches the server via stdio and uses JSON-RPC over stdin/stdout.
Tool/resource calls are forwarded to Byul endpoints and returned as-is with a summary.
# MCP Quickstart
Source: https://docs.byul.ai/mcp/quickstart
Get started with the @byul/mcp Model Context Protocol server
## Overview
`@byul/mcp` is a stdio-based MCP server that proxies the Byul REST API. It exposes a tool and a resource that forward requests to Byul endpoints and return the original JSON payload along with a brief summary string.
Requirements: Node.js 18+ and the `BYUL_API_KEY` environment variable
## Install and Run
```bash
BYUL_API_KEY=byul_api_key npx -y @byul/mcp
```
Once launched, your MCP-compatible client will communicate with the server via stdio.
## What’s Included
* Tool: `news_fetch` – proxies `GET /news` with filtering and pagination
* Resource: `byul://news{?limit,cursor,sinceId,minImportance,q,symbol,startDate,endDate}`
* Response: summary string (e.g., "Returned N articles") + original Byul API JSON
## Next Steps
Concepts and architecture
Client/editor integration
Tool specification
Resource specification
# byul://news
Source: https://docs.byul.ai/mcp/resources/news-resource
MCP resource - URL-based news retrieval
## Description
Use `byul://news{?limit,cursor,sinceId,minImportance,q,symbol,startDate,endDate}` to retrieve news with the same parameters as REST.
## Example
```txt
byul://news?limit=10&minImportance=7&symbol=AAPL
```
The resource payload matches the REST `GET /news` response format.
# MCP Setup
Source: https://docs.byul.ai/mcp/setup
Configure @byul/mcp in Cursor, Claude Code, Windsurf, and more
## Environment variable
```bash
export BYUL_API_KEY=byul_api_key
```
Never hardcode API keys. Use environment variables instead.
## Cursor
`~/.cursor/mcp.json` or project `.cursor/mcp.json`:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
## Claude Code (VS Code extension)
CLI:
```bash
claude mcp add -e BYUL_API_KEY=byul_api_key --scope user byul npx -- -y @byul/mcp
```
Settings JSON:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
## Claude Desktop
`claude_desktop_config.json`:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
## VS Code
Workspace `.vscode/mcp.json`:
```json
{
"mcpServers": {
"byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
## Windsurf
`windsurf_mcp.json`:
```json
{
"mcpServers": {
"mcp-server-byul": {
"command": "npx",
"args": ["-y", "@byul/mcp"],
"env": { "BYUL_API_KEY": "byul_api_key" }
}
}
}
```
# news_fetch
Source: https://docs.byul.ai/mcp/tools/news-fetch
MCP tool to fetch the latest financial news (proxies GET /news)
## Description
`news_fetch` proxies Byul's `GET /news`. Parameters are identical to the REST API.
## Parameters
Number of articles (1-100)
Pagination cursor
Articles created after this ID
Minimum importance (1-10)
Search query
Stock symbol
Start time (ISO 8601, UTC)
End time (ISO 8601, UTC)
## Request/Response Examples
```txt MCP Call
tools.call name="news_fetch" params={
"limit": 20,
"minImportance": 5,
"symbol": "AAPL",
"startDate": "2024-01-01T00:00:00.000Z",
"endDate": "2024-01-31T23:59:59.999Z"
}
```
```json Success
{
"summary": "Returned 20 articles",
"payload": {
"items": [
{ "_id": "67850d7b0123456789abcdef", "title": "Intel Announces New AI Chip Partnership", "content": "Intel Corporation announced a strategic partnership with Microsoft to develop next-generation AI chips for data centers. The collaboration will focus on optimizing AI workloads and improving energy efficiency in cloud computing infrastructure.", "koContent": "인텔 코포레이션이 마이크로소프트와 다음 세대 AI 칩 개발을 위한 전략적 파트너십을 발표했습니다. 이번 협력은 AI 워크로드 최적화와 클라우드 컴퓨팅 인프라의 에너지 효율성 향상에 중점을 둘 예정입니다.", "importanceScore": 8 }
],
"nextCursor": "67850d7b0123456789abcde0",
"hasMore": true
}
}
```
The `payload` structure matches the REST API `GET /news` response.
# Authentication
Source: https://docs.byul.ai/rest-api/authentication
API key authentication and security best practices
## API Key Authentication
Byul REST API uses API key authentication. All requests must include a valid API key in the request headers.
### Getting Your API Key
1. **Sign up** at [byul.ai](https://www.byul.ai)
2. **Login** to your [API Dashboard](https://www.byul.ai/api/dashboard)
3. **Copy** your API key (starts with `byul_v2`)
Your API key starts with the `byul_` prefix and is immediately available after account creation.
### Authentication Methods
Include your API key using the `X-API-Key` header:
```bash
X-API-Key: byul_api_key
```
### Example Requests
```bash
curl -X GET "https://api.byul.ai/api/v2/news?startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z" \
-H "X-API-Key: byul_api_key"
```
```javascript
const response = await fetch('https://api.byul.ai/api/v2/news', {
headers: {
'X-API-Key': process.env.BYUL_API_KEY
}
});
```
```python
import requests
response = requests.get(
'https://api.byul.ai/api/v2/news',
headers={'X-API-Key': os.getenv('BYUL_API_KEY')}
)
```
```php
$response = file_get_contents('https://api.byul.ai/api/v2/news', false,
stream_context_create([
'http' => [
'header' => 'X-API-Key: ' . getenv('BYUL_API_KEY')
]
])
);
```
## Security Best Practices
### Environment Variables
**Secure (Recommended)**
```bash
# Set environment variable
export BYUL_API_KEY=byul_api_key
# Use in your application
const apiKey = process.env.BYUL_API_KEY;
```
**Insecure (Don't do this)**
```javascript
// Never hardcode API keys in source code
const apiKey = 'byul_api_key';
```
### Client-Side Security
**Never expose API keys in client-side code**. API keys should only be used on your backend servers.
**Don't expose in browser**
```javascript
// This exposes your API key to all website visitors
const apiKey = 'byul_api_key';
fetch(`https://api.byul.ai/api/v2/news`, {
headers: { 'X-API-Key': apiKey }
});
```
**Use a backend proxy instead**
```javascript
// Frontend makes request to your backend
const response = await fetch('/api/news');
// Backend handles API key authentication
app.get('/api/news', async (req, res) => {
const response = await fetch('https://api.byul.ai/api/v2/news', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
res.json(await response.json());
});
```
### Key Management
1. **Rotate Keys Regularly**: Generate new API keys periodically
2. **Monitor Usage**: Check your dashboard for unusual activity
3. **Restrict Access**: Use separate keys for different environments
4. **Secure Storage**: Store keys in secure environment variables or key management systems
### Development Environments
Use different API keys for different environments:
```bash
# Development
BYUL_API_KEY=byul_api_key
# Production
BYUL_API_KEY=byul_api_key
```
## Authentication Errors
### 401 Unauthorized
```json
{
"statusCode": 401,
"message": "API key is required. Please provide a valid V2 API key in the X-API-Key header.",
"error": "Unauthorized",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Common causes:**
* Missing `X-API-Key` header
* Invalid API key format
* Expired or revoked API key
### 403 Forbidden
```json
{
"statusCode": 403,
"message": "Feature not available on current plan",
"error": "Forbidden",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Common causes:**
* Plan doesn't support the requested feature
* Account suspended or payment overdue
### 402 Payment Required
```json
{
"statusCode": 402,
"message": "Plan expired",
"error": "Payment Required",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Common causes:**
* Plan expired
* Payment method failed
* Usage exceeded plan limits
## Testing Authentication
Use the health check endpoint to test your authentication:
```bash
curl -X GET "https://api.byul.ai/api/v2/news/health" \
-H "X-API-Key: byul_api_key"
```
Success response:
```json
{
"status": "healthy",
"hasData": true
}
```
## Plan-Based Access
Different plans have different capabilities:
| Plan | Rate Limit | Features |
| -------------- | ----------- | --------------------------------- |
| Test (Free) | 30 req/min | Basic news access |
| Starter (\$19) | 60 req/min | Basic news access |
| Pro (\$99) | 120 req/min | News + WebSocket access |
| Enterprise | Custom | All features + custom development |
Check your current plan and usage in the [API Dashboard](https://www.byul.ai/api/dashboard).
## Next Steps
Learn about request structure and parameters
Implement proper error handling and retries
Understand rate limiting and optimization
Increase your rate limits and access WebSocket
# Error Handling
Source: https://docs.byul.ai/rest-api/error-handling
Handle API errors, rate limits, and implement retry logic
## Error Response Format
All API errors follow a consistent JSON format:
```json
{
"statusCode": 401,
"message": "API key is required. Please provide a valid V2 API key in the X-API-Key header.",
"error": "Unauthorized",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
### Error Fields
**`statusCode`** (integer)\
HTTP status code (400, 401, 403, 429, 500, etc.)
**`message`** (string)\
Human-readable error description
**`error`** (string)\
Error category/type
**`timestamp`** (string)\
When the error occurred (ISO 8601 UTC)
**`path`** (string)\
API endpoint that generated the error
## HTTP Status Codes
### 400 Bad Request
Invalid request parameters or malformed request.
```json
{
"statusCode": 400,
"message": "Limit must be between 1 and 100",
"error": "Bad Request",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Common causes:**
* `limit` parameter outside 1-100 range
* `minImportance` parameter outside 1-10 range
* Invalid cursor format
* Malformed query parameters
**Solution:**
```javascript
const validateParams = (params) => {
if (params.limit && (params.limit < 1 || params.limit > 100)) {
throw new Error('limit must be between 1 and 100');
}
if (params.minImportance && (params.minImportance < 1 || params.minImportance > 10)) {
throw new Error('minImportance must be between 1 and 10');
}
};
```
### 401 Unauthorized
Missing or invalid API key.
```json
{
"statusCode": 401,
"message": "API key is required. Please provide a valid V2 API key in the X-API-Key header.",
"error": "Unauthorized",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Common causes:**
* Missing `X-API-Key` header
* Invalid API key format (doesn't start with `byul_v2_`)
* Expired or revoked API key
**Solution:**
```javascript
const makeAuthenticatedRequest = async (endpoint, params = {}) => {
const apiKey = process.env.BYUL_API_KEY;
if (!apiKey || !apiKey.startsWith('byul_v2_')) {
throw new Error('Invalid API key format. Must start with byul_v2_');
}
const response = await fetch(`https://api.byul.ai/api/v2${endpoint}`, {
headers: { 'X-API-Key': apiKey }
});
if (response.status === 401) {
throw new Error('Authentication failed. Check your API key.');
}
return response;
};
```
### 402 Payment Required
Plan expired or payment issue.
```json
{
"statusCode": 402,
"message": "Plan expired",
"error": "Payment Required",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Solutions:**
* Update payment method in [dashboard](https://www.byul.ai/api/dashboard)
* Upgrade to a paid plan
* Contact support for billing issues
### 403 Forbidden
Feature not available on current plan.
```json
{
"statusCode": 403,
"message": "Feature not available on current plan",
"error": "Forbidden",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Solutions:**
* Upgrade to Pro or Enterprise plan
* Check [pricing page](https://www.byul.ai/api/pricing) for feature availability
### 429 Too Many Requests
Rate limit exceeded.
```json
{
"statusCode": 429,
"message": "Too many requests",
"error": "Too Many Requests",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Rate limits by plan:**
* Test: 30 requests/minute
* Starter: 60 requests/minute
* Pro/Enterprise: 120 requests/minute
**Headers included:**
```
X-V2-RateLimit-Limit: 120
X-V2-RateLimit-Remaining: 0
X-V2-RateLimit-Used: 120
X-V2-RateLimit-Reset: 1704628800
```
### 500 Internal Server Error
Server-side error.
```json
{
"statusCode": 500,
"message": "Internal server error",
"error": "Internal Server Error",
"timestamp": "2024-01-15T10:30:00.123Z",
"path": "/api/v2/news"
}
```
**Solutions:**
* Check [status page](https://www.byul.ai/status)
* Retry with exponential backoff
* Contact support if persistent
## Testing Error Scenarios
### Test Authentication Errors
Test missing API key (401 error):
```bash
curl -X GET "https://api.byul.ai/api/v2/news"
```
Test invalid API key (401 error):
```bash
curl -X GET "https://api.byul.ai/api/v2/news" \
-H "X-API-Key: invalid_key"
```
### Test Bad Request Errors
Test invalid limit parameter (400 error):
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=999" \
-H "X-API-Key: byul_api_key"
```
Test invalid importance score (400 error):
```bash
curl -X GET "https://api.byul.ai/api/v2/news?minImportance=99" \
-H "X-API-Key: byul_api_key"
```
### Test Rate Limits
Test rapid requests to trigger 429 error:
```bash
# Send multiple requests quickly
for i in {1..10}; do
curl -X GET "https://api.byul.ai/api/v2/news" \
-H "X-API-Key: byul_api_key" &
done
wait
```
### Check Rate Limit Headers
View current rate limit status:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key" \
-I # Include response headers
```
## Retry Logic
### Exponential Backoff
Implement retry logic with exponential backoff for temporary failures:
```javascript
const exponentialBackoff = async (
fn,
maxRetries = 3,
baseDelay = 1000
) => {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
const isRetryable = [429, 500, 502, 503, 504].includes(error.status);
if (!isRetryable || attempt === maxRetries - 1) {
throw error;
}
const delay = baseDelay * Math.pow(2, attempt);
const jitter = Math.random() * 1000; // Add jitter to prevent thundering herd
console.log(`Retry attempt ${attempt + 1} after ${delay + jitter}ms`);
await new Promise(resolve => setTimeout(resolve, delay + jitter));
}
}
};
// Usage
const getNewsWithRetry = async () => {
return exponentialBackoff(async () => {
const response = await fetch('https://api.byul.ai/api/v2/news', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
if (!response.ok) {
const error = new Error(`HTTP ${response.status}`);
error.status = response.status;
throw error;
}
return response.json();
});
};
```
### Rate Limit Handling
Handle rate limits gracefully:
```javascript
const makeRateLimitAwareRequest = async (endpoint, params = {}) => {
const response = await fetch(`https://api.byul.ai/api/v2${endpoint}`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
// Check rate limit headers
const rateLimit = {
limit: parseInt(response.headers.get('X-V2-RateLimit-Limit')),
remaining: parseInt(response.headers.get('X-V2-RateLimit-Remaining')),
used: parseInt(response.headers.get('X-V2-RateLimit-Used')),
reset: parseInt(response.headers.get('X-V2-RateLimit-Reset'))
};
if (response.status === 429) {
const resetTime = new Date(rateLimit.reset * 1000);
const waitTime = resetTime - new Date();
console.log(`Rate limited. Waiting ${waitTime}ms until ${resetTime}`);
await new Promise(resolve => setTimeout(resolve, waitTime));
// Retry the request
return makeRateLimitAwareRequest(endpoint, params);
}
// Warn when approaching rate limit
if (rateLimit.remaining < 10) {
console.warn(`Low rate limit remaining: ${rateLimit.remaining}/${rateLimit.limit}`);
}
return response.json();
};
```
## Error Handling Patterns
### Comprehensive Error Handler
```javascript
class ByulAPIError extends Error {
constructor(statusCode, message, error, path) {
super(message);
this.name = 'ByulAPIError';
this.statusCode = statusCode;
this.error = error;
this.path = path;
}
}
const handleApiResponse = async (response) => {
if (response.ok) {
return response.json();
}
const errorData = await response.json().catch(() => ({}));
throw new ByulAPIError(
response.status,
errorData.message || `HTTP ${response.status}`,
errorData.error || 'Unknown Error',
errorData.path || response.url
);
};
const safeApiCall = async (endpoint, options = {}) => {
try {
const response = await fetch(`https://api.byul.ai/api/v2${endpoint}`, {
...options,
headers: {
'X-API-Key': process.env.BYUL_API_KEY,
...options.headers
}
});
return await handleApiResponse(response);
} catch (error) {
if (error instanceof ByulAPIError) {
switch (error.statusCode) {
case 400:
console.error('Bad Request:', error.message);
break;
case 401:
console.error('Authentication failed:', error.message);
break;
case 402:
console.error('Payment required:', error.message);
break;
case 403:
console.error('Forbidden:', error.message);
break;
case 429:
console.error('Rate limited:', error.message);
break;
case 500:
console.error('Server error:', error.message);
break;
default:
console.error('API error:', error.message);
}
}
throw error;
}
};
```
### Circuit Breaker Pattern
Implement circuit breaker to handle persistent failures:
```javascript
class CircuitBreaker {
constructor(threshold = 5, timeout = 60000) {
this.threshold = threshold;
this.timeout = timeout;
this.failureCount = 0;
this.lastFailTime = null;
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
}
async call(fn) {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailTime > this.timeout) {
this.state = 'HALF_OPEN';
} else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failureCount = 0;
this.state = 'CLOSED';
}
onFailure() {
this.failureCount++;
this.lastFailTime = Date.now();
if (this.failureCount >= this.threshold) {
this.state = 'OPEN';
}
}
}
const apiCircuitBreaker = new CircuitBreaker();
const resilientApiCall = async (endpoint) => {
return apiCircuitBreaker.call(async () => {
return safeApiCall(endpoint);
});
};
```
## Monitoring and Alerting
### Health Check Implementation
```javascript
const healthCheck = async () => {
try {
const response = await fetch('https://api.byul.ai/api/v2/news/health');
const data = await response.json();
if (data.status === 'healthy' && data.hasData) {
return { healthy: true, message: 'API is operational' };
} else {
return { healthy: false, message: 'API reports unhealthy status' };
}
} catch (error) {
return { healthy: false, message: `Health check failed: ${error.message}` };
}
};
// Run health checks periodically
setInterval(async () => {
const health = await healthCheck();
if (!health.healthy) {
console.error('API Health Alert:', health.message);
// Send alert to monitoring system
}
}, 60000); // Check every minute
```
### Request Logging
```javascript
const loggedApiCall = async (endpoint, params = {}) => {
const startTime = Date.now();
const requestId = Math.random().toString(36).substr(2, 9);
console.log(`[${requestId}] API Request: ${endpoint}`, params);
try {
const result = await safeApiCall(endpoint, params);
const duration = Date.now() - startTime;
console.log(`[${requestId}] API Success: ${duration}ms`, {
itemCount: result.items?.length,
hasMore: result.hasMore
});
return result;
} catch (error) {
const duration = Date.now() - startTime;
console.error(`[${requestId}] API Error: ${duration}ms`, {
status: error.statusCode,
message: error.message
});
throw error;
}
};
```
## Error Recovery Strategies
### Graceful Degradation
```javascript
const getNewsWithFallback = async (filters = {}) => {
try {
// Try primary endpoint
return await safeApiCall('/news', { method: 'GET' });
} catch (error) {
if (error.statusCode >= 500) {
// Server error - try health check endpoint as fallback
console.warn('Primary endpoint failed, checking service health');
const health = await healthCheck();
if (!health.healthy) {
// Return cached data or empty state
return { items: [], hasMore: false, error: 'Service temporarily unavailable' };
}
}
throw error;
}
};
```
### Data Caching
```javascript
class NewsCache {
constructor(ttlMs = 300000) { // 5 minute TTL
this.cache = new Map();
this.ttl = ttlMs;
}
get(key) {
const item = this.cache.get(key);
if (!item) return null;
if (Date.now() - item.timestamp > this.ttl) {
this.cache.delete(key);
return null;
}
return item.data;
}
set(key, data) {
this.cache.set(key, {
data,
timestamp: Date.now()
});
}
}
const newsCache = new NewsCache();
const getCachedNews = async (filters = {}) => {
const cacheKey = JSON.stringify(filters);
const cached = newsCache.get(cacheKey);
if (cached) {
console.log('Returning cached data');
return cached;
}
try {
const data = await safeApiCall('/news');
newsCache.set(cacheKey, data);
return data;
} catch (error) {
// Return stale cache if available during errors
const stale = newsCache.cache.get(cacheKey);
if (stale) {
console.warn('Returning stale cached data due to API error');
return stale.data;
}
throw error;
}
};
```
# cURL
Source: https://docs.byul.ai/rest-api/examples/curl
Complete cURL examples for testing and integrating Byul REST API
**Pro Tip**: cURL examples work on all platforms (Linux, macOS, Windows) and are perfect for testing API endpoints before implementing in your application.
## Basic News Retrieval
### Get Latest News
Fetch the most recent financial news:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=10" \
-H "X-API-Key: byul_api_key" \
-H "Content-Type: application/json"
```
### High-Importance News Only
Get only market-moving news with importance score 8+:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=5&minImportance=8" \
-H "X-API-Key: byul_api_key" \
-H "Content-Type: application/json"
```
### Breaking News with Formatting
Get breaking news with formatted output:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=3&minImportance=9" \
-H "X-API-Key: byul_api_key" \
-H "Content-Type: application/json" \
| jq '.items[] | {title: .title, importance: .importanceScore, date: .date}'
```
**Install jq**: Use `brew install jq` (macOS) or `apt-get install jq` (Ubuntu) to format JSON output.
## Advanced Filtering
### Symbol-Specific News
Get news for specific stocks or ETFs:
```bash
# Apple (AAPL) news
curl -X GET "https://api.byul.ai/api/v2/news?symbol=AAPL&limit=10" \
-H "X-API-Key: byul_api_key"
# Multiple symbols (use separate requests)
curl -X GET "https://api.byul.ai/api/v2/news?symbol=TSLA&minImportance=7" \
-H "X-API-Key: byul_api_key"
```
### Search by Keywords
### Date Range Filtering
Filter by a specific date window using ISO 8601 timestamps:
```bash
# January 2024
curl -X GET "https://api.byul.ai/api/v2/news?startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z" \
-H "X-API-Key: byul_api_key"
# After a given date
curl -X GET "https://api.byul.ai/api/v2/news?startDate=2024-01-15T00:00:00.000Z" \
-H "X-API-Key: byul_api_key"
# Before a given date
curl -X GET "https://api.byul.ai/api/v2/news?endDate=2024-01-15T23:59:59.999Z" \
-H "X-API-Key: byul_api_key"
```
Search for specific topics or events:
```bash
# Fed-related news
curl -X GET "https://api.byul.ai/api/v2/news?q=federal%20reserve&minImportance=6" \
-H "X-API-Key: byul_api_key"
# Earnings announcements
curl -X GET "https://api.byul.ai/api/v2/news?q=earnings&minImportance=7&limit=20" \
-H "X-API-Key: byul_api_key"
```
## Pagination
### Using Cursors
Handle large result sets with pagination:
```bash
# First page
curl -X GET "https://api.byul.ai/api/v2/news?limit=50" \
-H "X-API-Key: byul_api_key" \
> first_page.json
# Extract nextCursor from response
NEXT_CURSOR=$(cat first_page.json | jq -r '.nextCursor')
# Second page
curl -X GET "https://api.byul.ai/api/v2/news?limit=50&cursor=$NEXT_CURSOR" \
-H "X-API-Key: byul_api_key"
```
### Since ID Filtering
Get news after a specific article:
```bash
# Get latest news first
LATEST_ID=$(curl -s -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key" | jq -r '.items[0]._id')
# Later, get news since that ID
curl -X GET "https://api.byul.ai/api/v2/news?sinceId=$LATEST_ID" \
-H "X-API-Key: byul_api_key"
```
## Response Handling
### Save to File
Save API responses for analysis:
```bash
# Save raw JSON
curl -X GET "https://api.byul.ai/api/v2/news?minImportance=8&limit=100" \
-H "X-API-Key: byul_api_key" \
-o market_news.json
# Save formatted output
curl -X GET "https://api.byul.ai/api/v2/news?minImportance=8&limit=50" \
-H "X-API-Key: byul_api_key" \
| jq '.items[] | {title, importance: .importanceScore, symbols, date}' \
> formatted_news.json
```
### Extract Specific Fields
Get only the information you need:
```bash
# Just titles and importance scores
curl -s -X GET "https://api.byul.ai/api/v2/news?minImportance=7&limit=10" \
-H "X-API-Key: byul_api_key" \
| jq -r '.items[] | "\(.importanceScore)/10: \(.title)"'
# Stock symbols and news count
curl -s -X GET "https://api.byul.ai/api/v2/news?limit=100" \
-H "X-API-Key: byul_api_key" \
| jq -r '.items[].symbols[]?' | sort | uniq -c | sort -nr
```
## Error Handling
### Check API Status
Verify API availability and your authentication:
```bash
# Test connection
curl -I -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key"
# Check rate limit headers
curl -v -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key" 2>&1 | grep -i "x-v2-ratelimit"
```
### Handle Rate Limits
Check remaining rate limit:
```bash
# Get rate limit information
curl -s -I -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key" | grep -i "x-v2-ratelimit"
```
### Retry Logic with Backoff
Implement retry logic in shell scripts:
```bash
#!/bin/bash
API_KEY="byul_api_key"
MAX_RETRIES=3
RETRY_DELAY=1
for i in $(seq 1 $MAX_RETRIES); do
response=$(curl -s -w "HTTPSTATUS:%{http_code}" \
-X GET "https://api.byul.ai/api/v2/news?minImportance=8&limit=10" \
-H "X-API-Key: $API_KEY")
http_code=$(echo $response | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
body=$(echo $response | sed -e 's/HTTPSTATUS:.*//g')
if [ $http_code -eq 200 ]; then
echo $body | jq '.'
break
elif [ $http_code -eq 429 ]; then
echo "Rate limited, retrying in ${RETRY_DELAY}s..."
sleep $RETRY_DELAY
RETRY_DELAY=$((RETRY_DELAY * 2)) # Exponential backoff
else
echo "Error: HTTP $http_code"
echo $body
break
fi
done
```
## Monitoring and Automation
### Real-time Monitoring Script
Create a monitoring script for breaking news:
```bash
#!/bin/bash
API_KEY="byul_api_key"
LAST_CHECK=""
while true; do
# Get high-importance news
if [ -n "$LAST_CHECK" ]; then
response=$(curl -s "https://api.byul.ai/api/v2/news?minImportance=8&sinceId=$LAST_CHECK" \
-H "X-API-Key: $API_KEY")
else
response=$(curl -s "https://api.byul.ai/api/v2/news?minImportance=8&limit=5" \
-H "X-API-Key: $API_KEY")
fi
# Process new articles
echo $response | jq -r '.items[]? | "BREAKING: \(.title) (Importance: \(.importanceScore)/10)"'
# Update last check
LAST_CHECK=$(echo $response | jq -r '.items[0]._id // empty')
sleep 30 # Check every 30 seconds
done
```
### CI/CD Integration
Use in automated testing:
```bash
# Test API in CI pipeline
#!/bin/bash
set -e
echo "Testing Byul API connectivity..."
response=$(curl -s -w "HTTPSTATUS:%{http_code}" \
-X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: $BYUL_API_KEY")
http_code=$(echo $response | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
if [ $http_code -eq 200 ]; then
echo "✓ API connection successful"
else
echo "✗ API connection failed with code: $http_code"
exit 1
fi
```
## Performance Testing
### Latency Testing
Measure API response times:
```bash
# Single request timing
time curl -s -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key" > /dev/null
# Multiple requests with timing
for i in {1..10}; do
time_result=$(time ( curl -s -X GET "https://api.byul.ai/api/v2/news?limit=10" \
-H "X-API-Key: byul_api_key" > /dev/null ) 2>&1 )
echo "Request $i: $time_result"
done
```
### Load Testing
Test with multiple concurrent requests:
```bash
# Simple parallel requests
for i in {1..5}; do
curl -s -X GET "https://api.byul.ai/api/v2/news?limit=10" \
-H "X-API-Key: byul_api_key" &
done
wait
echo "All requests completed"
```
## Environment Variables
Set up environment variables for security:
```bash
# Export your API key
export BYUL_API_KEY="byul_api_key"
# Use in requests
curl -X GET "https://api.byul.ai/api/v2/news?minImportance=8" \
-H "X-API-Key: $BYUL_API_KEY"
# Or from file
curl -X GET "https://api.byul.ai/api/v2/news?limit=10" \
-H "X-API-Key: $(cat ~/.byul_api_key)"
```
**Security Best Practice**: Never hardcode API keys in scripts. Always use environment variables or secure files with proper permissions.
## Next Steps
Build production applications with Node.js
Data analysis and algorithmic trading with Python
Implement robust error handling strategies
Optimize API usage and manage rate limits
# Node.js
Source: https://docs.byul.ai/rest-api/examples/nodejs
Complete Node.js examples for REST API integration
## Basic Usage
### Simple News Fetch
```javascript
const fetch = require('node-fetch');
const getNews = async () => {
const response = await fetch('https://api.byul.ai/api/v2/news?limit=10&minImportance=7&startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z', {
headers: {
'X-API-Key': process.env.BYUL_API_KEY
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
data.items.forEach(article => {
console.log(`${article.title} - Importance: ${article.importanceScore}/10`);
});
return data;
};
getNews();
```
### With Error Handling
```javascript
const fetch = require('node-fetch');
const safeGetNews = async (filters = {}) => {
try {
const params = new URLSearchParams({
limit: '20',
minImportance: '6',
...filters
});
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: {
'X-API-Key': process.env.BYUL_API_KEY
}
});
if (!response.ok) {
const errorData = await response.json();
console.error('API Error:', errorData.message);
return null;
}
return await response.json();
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
};
// Usage
safeGetNews({ symbol: 'AAPL', startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-31T23:59:59.999Z' });
```
## Express.js Integration
### News API Proxy
```javascript
const express = require('express');
const fetch = require('node-fetch');
const rateLimit = require('express-rate-limit');
const app = express();
const PORT = process.env.PORT || 3000;
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
app.use(express.json());
// News endpoint
app.get('/api/news', async (req, res) => {
try {
const { limit = 10, minImportance = 1, symbol, q } = req.query;
// Validate parameters
if (limit < 1 || limit > 100) {
return res.status(400).json({ error: 'limit must be between 1 and 100' });
}
const params = new URLSearchParams({ limit, minImportance });
if (symbol) params.append('symbol', symbol);
if (q) params.append('q', q);
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
if (!response.ok) {
const errorData = await response.json();
return res.status(response.status).json(errorData);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('News API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
```
## Advanced Examples
### News Aggregator Class
```javascript
const fetch = require('node-fetch');
class ByulNewsClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.byul.ai/api/v2';
this.cache = new Map();
}
async makeRequest(endpoint, params = {}) {
const url = new URL(`${this.baseUrl}${endpoint}`);
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
url.searchParams.append(key, value.toString());
}
});
const response = await fetch(url, {
headers: { 'X-API-Key': this.apiKey }
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`API Error: ${errorData.message}`);
}
return response.json();
}
async getNews(filters = {}) {
return this.makeRequest('/news', filters);
}
async getAllNews(filters = {}) {
let allNews = [];
let cursor = null;
let hasMore = true;
while (hasMore) {
const data = await this.getNews({
...filters,
cursor,
limit: 100
});
allNews.push(...data.items);
cursor = data.nextCursor;
hasMore = data.hasMore;
// Prevent infinite loops
if (allNews.length > 10000) break;
}
return allNews;
}
async getPortfolioNews(symbols, minImportance = 6) {
const promises = symbols.map(symbol =>
this.getNews({ symbol, minImportance, limit: 50 })
);
const results = await Promise.all(promises);
// Combine and deduplicate
const newsMap = new Map();
results.forEach(data => {
data.items.forEach(article => {
newsMap.set(article._id, article);
});
});
return Array.from(newsMap.values())
.sort((a, b) => b.importanceScore - a.importanceScore);
}
}
// Usage
const client = new ByulNewsClient(process.env.BYUL_API_KEY);
// Get breaking news
client.getNews({ minImportance: 9, startDate: '2024-01-01T00:00:00.000Z' })
.then(data => console.log('Breaking news:', data.items.length))
.catch(console.error);
// Get portfolio news
client.getPortfolioNews(['AAPL', 'GOOGL', 'MSFT'])
.then(news => console.log('Portfolio news:', news.length))
.catch(console.error);
```
### Real-time News Monitor
```javascript
const EventEmitter = require('events');
class NewsMonitor extends EventEmitter {
constructor(apiKey, pollInterval = 30000) {
super();
this.apiKey = apiKey;
this.pollInterval = pollInterval;
this.lastArticleId = null;
this.isRunning = false;
}
async checkForNewNews() {
try {
const params = { limit: 50, minImportance: 6 };
if (this.lastArticleId) {
params.sinceId = this.lastArticleId;
}
const response = await fetch(`https://api.byul.ai/api/v2/news?${new URLSearchParams(params)}`, {
headers: { 'X-API-Key': this.apiKey }
});
if (!response.ok) {
this.emit('error', new Error(`HTTP ${response.status}`));
return;
}
const data = await response.json();
if (data.items.length > 0) {
this.lastArticleId = data.items[0]._id;
this.emit('news', data.items);
// Emit breaking news separately
const breakingNews = data.items.filter(article => article.importanceScore >= 9);
if (breakingNews.length > 0) {
this.emit('breaking', breakingNews);
}
}
} catch (error) {
this.emit('error', error);
}
}
start() {
if (this.isRunning) return;
this.isRunning = true;
this.intervalId = setInterval(() => {
this.checkForNewNews();
}, this.pollInterval);
// Check immediately
this.checkForNewNews();
this.emit('started');
}
stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
this.isRunning = false;
this.emit('stopped');
}
}
// Usage
const monitor = new NewsMonitor(process.env.BYUL_API_KEY, 30000);
monitor.on('started', () => {
console.log('News monitoring started');
});
monitor.on('news', (articles) => {
console.log(`📰 Found ${articles.length} new articles`);
articles.forEach(article => {
console.log(` ${article.title} (${article.importanceScore}/10)`);
});
});
monitor.on('breaking', (articles) => {
console.log('BREAKING NEWS:');
articles.forEach(article => {
console.log(` ${article.title}`);
});
});
monitor.on('error', (error) => {
console.error('Monitor error:', error.message);
});
monitor.start();
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\n🛑 Shutting down news monitor...');
monitor.stop();
process.exit(0);
});
```
### Webhook Server
```javascript
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
// News data storage (in production, use a database)
let newsCache = [];
// Simulate webhook endpoint (Byul doesn't have webhooks yet, but this shows the pattern)
app.post('/webhook/news', (req, res) => {
try {
// In a real webhook, you'd verify the signature
const { articles } = req.body;
// Process new articles
articles.forEach(article => {
// Add to cache
newsCache.unshift(article);
// Keep only latest 1000 articles
newsCache = newsCache.slice(0, 1000);
// Log high-importance news
if (article.importanceScore >= 8) {
console.log(`High impact: ${article.title}`);
}
});
res.json({ received: articles.length });
} catch (error) {
console.error('Webhook error:', error);
res.status(500).json({ error: 'Webhook processing failed' });
}
});
// Serve cached news
app.get('/api/cached-news', (req, res) => {
const { limit = 20, minImportance } = req.query;
let filtered = newsCache;
if (minImportance) {
filtered = filtered.filter(article =>
article.importanceScore >= parseInt(minImportance)
);
}
res.json({
items: filtered.slice(0, parseInt(limit)),
total: filtered.length,
cached: true
});
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
```
## Environment Setup
### package.json
```json
{
"name": "byul-news-client",
"version": "1.0.0",
"description": "Byul AI News API client",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
},
"dependencies": {
"node-fetch": "^2.6.7",
"express": "^4.18.0",
"express-rate-limit": "^6.7.0"
},
"devDependencies": {
"nodemon": "^2.0.20",
"jest": "^29.0.0"
}
}
```
### Environment Variables
Create `.env` file:
```bash
BYUL_API_KEY=byul_api_key
NODE_ENV=development
PORT=3000
```
### Installation and Run
```bash
# Install dependencies
npm install
# Set environment variable
export BYUL_API_KEY=byul_api_key
# Run the application
npm start
```
## Testing
### Unit Tests
```javascript
const { describe, it, expect, beforeEach, jest } = require('@jest/globals');
const ByulNewsClient = require('./byul-client');
// Mock fetch
global.fetch = jest.fn();
describe('ByulNewsClient', () => {
let client;
beforeEach(() => {
client = new ByulNewsClient('test_api_key');
fetch.mockClear();
});
it('should fetch news successfully', async () => {
const mockResponse = {
items: [
{
_id: '123',
title: 'Test News',
importanceScore: 8
}
],
hasMore: false
};
fetch.mockResolvedValueOnce({
ok: true,
json: async () => mockResponse
});
const result = await client.getNews({ limit: 10 });
expect(result).toEqual(mockResponse);
expect(fetch).toHaveBeenCalledWith(
expect.stringContaining('/news?limit=10'),
expect.objectContaining({
headers: { 'X-API-Key': 'test_api_key' }
})
);
});
it('should handle API errors', async () => {
fetch.mockResolvedValueOnce({
ok: false,
status: 401,
json: async () => ({ message: 'Unauthorized' })
});
await expect(client.getNews()).rejects.toThrow('API Error: Unauthorized');
});
});
```
Run tests:
```bash
npm test
```
# PHP
Source: https://docs.byul.ai/rest-api/examples/php
Complete PHP examples for REST API integration
## Basic Usage
### Simple News Fetch
```php
$limit,
'minImportance' => $minImportance
];
if ($startDate) { $params['startDate'] = $startDate; }
if ($endDate) { $params['endDate'] = $endDate; }
$url = 'https://api.byul.ai/api/v2/news?' . http_build_query($params);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'X-API-Key: ' . $apiKey,
'timeout' => 30
]
]);
$response = file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception('Failed to fetch news');
}
$data = json_decode($response, true);
if ($data === null) {
throw new Exception('Invalid JSON response');
}
echo "Retrieved " . count($data['items']) . " articles\n";
foreach ($data['items'] as $article) {
echo "{$article['title']} - Importance: {$article['importanceScore']}/10\n";
}
return $data;
}
// Usage
try {
$news = getNews(10, 7, '2024-01-01T00:00:00.000Z', '2024-01-31T23:59:59.999Z');
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
```
### Using cURL with Error Handling
```php
statusCode = $statusCode;
$this->errorType = $errorType;
}
}
function safeGetNews($filters = []) {
$apiKey = getenv('BYUL_API_KEY');
if (!$apiKey) {
throw new ByulAPIException('BYUL_API_KEY environment variable not set');
}
// Default parameters
$params = array_merge([
'limit' => 20,
'minImportance' => 6
], $filters);
$url = 'https://api.byul.ai/api/v2/news?' . http_build_query($params);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . $apiKey],
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_USERAGENT => 'Byul-PHP-Client/1.0'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
throw new ByulAPIException("cURL error: $curlError");
}
$data = json_decode($response, true);
if ($httpCode !== 200) {
$message = $data['message'] ?? "HTTP $httpCode";
$errorType = $data['error'] ?? 'HTTP Error';
throw new ByulAPIException($message, $httpCode, $errorType);
}
return $data;
}
// Usage with error handling
try {
$news = safeGetNews(['symbol' => 'AAPL']);
echo "Found " . count($news['items']) . " AAPL articles\n";
} catch (ByulAPIException $e) {
switch ($e->statusCode) {
case 401:
echo "Authentication failed: Check your API key\n";
break;
case 429:
echo "Rate limit exceeded: Please wait before retrying\n";
break;
case 400:
echo "Bad request: " . $e->getMessage() . "\n";
break;
default:
echo "API Error ({$e->statusCode}): " . $e->getMessage() . "\n";
}
}
?>
```
## Laravel Integration
### News Service Class
```php
baseUrl = 'https://api.byul.ai/api/v2';
$this->apiKey = config('services.byul.api_key');
}
public function getNews(array $filters = []): array
{
$cacheKey = 'byul_news_' . md5(serialize($filters));
return Cache::remember($cacheKey, 300, function () use ($filters) {
return $this->makeRequest('/news', $filters);
});
}
public function getHealthStatus(): array
{
return $this->makeRequest('/news/health');
}
public function getAllNews(array $filters = []): array
{
$allNews = [];
$cursor = null;
$maxPages = 100; // Safety limit
$currentPage = 0;
do {
$params = array_merge($filters, ['limit' => 100]);
if ($cursor) {
$params['cursor'] = $cursor;
}
$data = $this->makeRequest('/news', $params);
$allNews = array_merge($allNews, $data['items']);
$cursor = $data['nextCursor'] ?? null;
$hasMore = $data['hasMore'] ?? false;
$currentPage++;
} while ($hasMore && $cursor && $currentPage < $maxPages);
return $allNews;
}
public function getPortfolioNews(array $symbols, int $minImportance = 6): array
{
$allNews = [];
$seenIds = [];
foreach ($symbols as $symbol) {
try {
$data = $this->getNews([
'symbol' => $symbol,
'minImportance' => $minImportance,
'limit' => 50
]);
foreach ($data['items'] as $article) {
if (!in_array($article['_id'], $seenIds)) {
$allNews[] = $article;
$seenIds[] = $article['_id'];
}
}
} catch (\Exception $e) {
Log::warning("Failed to fetch news for symbol $symbol: " . $e->getMessage());
}
}
// Sort by importance
usort($allNews, function ($a, $b) {
return $b['importanceScore'] - $a['importanceScore'];
});
return $allNews;
}
private function makeRequest(string $endpoint, array $params = []): array
{
$response = Http::withHeaders([
'X-API-Key' => $this->apiKey
])
->timeout(30)
->get($this->baseUrl . $endpoint, $params);
if ($response->failed()) {
$errorData = $response->json();
$message = $errorData['message'] ?? 'API request failed';
Log::error("Byul API error: $message", [
'status' => $response->status(),
'endpoint' => $endpoint,
'params' => $params
]);
throw new \Exception("API Error: $message", $response->status());
}
return $response->json();
}
}
```
### Laravel Controller
```php
newsService = $newsService;
}
public function index(Request $request): JsonResponse
{
$request->validate([
'limit' => 'integer|min:1|max:100',
'minImportance' => 'integer|min:1|max:10',
'symbol' => 'string|max:10',
'q' => 'string|max:100'
]);
try {
$filters = $request->only(['limit', 'minImportance', 'symbol', 'q']);
$news = $this->newsService->getNews($filters);
return response()->json($news);
} catch (\Exception $e) {
return response()->json([
'error' => 'Failed to fetch news',
'message' => $e->getMessage()
], 500);
}
}
public function portfolio(Request $request): JsonResponse
{
$request->validate([
'symbols' => 'required|array|min:1',
'symbols.*' => 'string|max:10',
'minImportance' => 'integer|min:1|max:10'
]);
try {
$symbols = $request->input('symbols');
$minImportance = $request->input('minImportance', 6);
$news = $this->newsService->getPortfolioNews($symbols, $minImportance);
return response()->json([
'items' => $news,
'count' => count($news),
'symbols' => $symbols
]);
} catch (\Exception $e) {
return response()->json([
'error' => 'Failed to fetch portfolio news',
'message' => $e->getMessage()
], 500);
}
}
public function health(): JsonResponse
{
try {
$status = $this->newsService->getHealthStatus();
return response()->json($status);
} catch (\Exception $e) {
return response()->json([
'status' => 'unhealthy',
'message' => $e->getMessage()
], 503);
}
}
}
```
### Routes
```php
middleware(['throttle:100,1'])->group(function () {
Route::get('/news', [NewsController::class, 'index']);
Route::post('/news/portfolio', [NewsController::class, 'portfolio']);
Route::get('/health', [NewsController::class, 'health']);
});
```
### Configuration
```php
[
'api_key' => env('BYUL_API_KEY'),
],
];
```
## Advanced Examples
### WordPress Plugin
```php
'Display latest financial news from Byul AI']
);
}
public function widget($args, $instance)
{
echo $args['before_widget'];
$title = apply_filters('widget_title', $instance['title']);
if (!empty($title)) {
echo $args['before_title'] . $title . $args['after_title'];
}
$limit = $instance['limit'] ?? 5;
$minImportance = $instance['min_importance'] ?? 7;
$news = $this->getNews($limit, $minImportance);
if ($news) {
echo '
';
} else {
echo 'Unable to load news at this time.
';
}
echo $args['after_widget'];
}
public function form($instance)
{
$title = $instance['title'] ?? 'Financial News';
$limit = $instance['limit'] ?? 5;
$minImportance = $instance['min_importance'] ?? 7;
?>
Title:
Number of articles:
Minimum importance (1-10):
$limit,
'minImportance' => $minImportance
]);
$response = wp_remote_get($url, [
'timeout' => 30,
'headers' => ['X-API-Key' => $apiKey]
]);
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if ($data && isset($data['items'])) {
// Cache for 5 minutes
set_transient($transient_key, $data, 300);
return $data;
}
return false;
}
}
// Register widget
function register_byul_news_widget()
{
register_widget('ByulNewsWidget');
}
add_action('widgets_init', 'register_byul_news_widget');
// Admin settings page
function byul_news_admin_menu()
{
add_options_page(
'Byul News Settings',
'Byul News',
'manage_options',
'byul-news-settings',
'byul_news_settings_page'
);
}
add_action('admin_menu', 'byul_news_admin_menu');
function byul_news_settings_page()
{
if (isset($_POST['submit'])) {
update_option('byul_api_key', sanitize_text_field($_POST['byul_api_key']));
echo '';
}
$apiKey = get_option('byul_api_key', '');
?>
storage = $storage;
$this->prefix = $prefix;
}
public function isAllowed(string $key, int $limit = 100, int $window = 3600): bool
{
$fullKey = $this->prefix . $key;
$now = time();
// Get current requests
$requests = $this->getRequests($fullKey);
// Filter out expired requests
$requests = array_filter($requests, function($timestamp) use ($now, $window) {
return ($now - $timestamp) < $window;
});
if (count($requests) < $limit) {
// Add current request
$requests[] = $now;
$this->setRequests($fullKey, $requests, $window);
return true;
}
return false;
}
private function getRequests(string $key): array
{
if ($this->storage === 'file') {
$filename = sys_get_temp_dir() . '/' . $key;
if (file_exists($filename)) {
$data = file_get_contents($filename);
return json_decode($data, true) ?: [];
}
}
return [];
}
private function setRequests(string $key, array $requests, int $ttl): void
{
if ($this->storage === 'file') {
$filename = sys_get_temp_dir() . '/' . $key;
file_put_contents($filename, json_encode($requests));
// Set file expiration (basic cleanup)
touch($filename, time() + $ttl);
}
}
public function getRemaining(string $key, int $limit = 100, int $window = 3600): int
{
$fullKey = $this->prefix . $key;
$now = time();
$requests = $this->getRequests($fullKey);
$requests = array_filter($requests, function($timestamp) use ($now, $window) {
return ($now - $timestamp) < $window;
});
return max(0, $limit - count($requests));
}
}
// Usage in API client
class RateLimitedByulClient
{
private $apiKey;
private $rateLimiter;
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
$this->rateLimiter = new RateLimiter();
}
public function getNews(array $filters = []): array
{
$clientId = 'api_' . md5($this->apiKey);
if (!$this->rateLimiter->isAllowed($clientId, 60, 60)) { // 60 requests per minute
$remaining = $this->rateLimiter->getRemaining($clientId, 60, 60);
throw new Exception("Rate limit exceeded. Try again in " . (60 - $remaining) . " seconds.");
}
// Make API request
$url = 'https://api.byul.ai/api/v2/news?' . http_build_query($filters);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . $this->apiKey],
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("API request failed with status $httpCode");
}
return json_decode($response, true);
}
}
```
## Environment Setup
### Composer Setup
```json
{
"name": "your-company/byul-news-client",
"description": "PHP client for Byul AI News API",
"type": "library",
"require": {
"php": ">=7.4",
"guzzlehttp/guzzle": "^7.0",
"monolog/monolog": "^2.0"
},
"require-dev": {
"phpunit/phpunit": "^9.0",
"squizlabs/php_codesniffer": "^3.6"
},
"autoload": {
"psr-4": {
"ByulNews\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"ByulNews\\Tests\\": "tests/"
}
}
}
```
### Installation
```bash
# Install dependencies
composer install
# Set environment variable
export BYUL_API_KEY=byul_api_key
# Run the example
php examples/basic_usage.php
```
### Using with .env file
```php
Dict:
"""Fetch news from Byul AI API"""
response = requests.get(
'https://api.byul.ai/api/v2/news',
params={
'limit': limit,
'minImportance': min_importance,
**({'startDate': start_date} if start_date else {}),
**({'endDate': end_date} if end_date else {})
},
headers={
'X-API-Key': os.getenv('BYUL_API_KEY')
}
)
response.raise_for_status() # Raises HTTPError for bad status codes
data = response.json()
print(f"Retrieved {len(data['items'])} articles")
for article in data['items']:
print(f"{article['title']} - Importance: {article['importanceScore']}/10")
return data
# Usage
if __name__ == "__main__":
news = get_news(start_date='2024-01-01T00:00:00.000Z', end_date='2024-01-31T23:59:59.999Z')
```
### With Error Handling
```python
import requests
import os
import logging
from typing import Dict, Optional
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def safe_get_news(filters: Dict = None) -> Optional[Dict]:
"""Safely fetch news with comprehensive error handling"""
if filters is None:
filters = {}
# Default parameters
params = {
'limit': 20,
'minImportance': 6,
**filters
}
try:
response = requests.get(
'https://api.byul.ai/api/v2/news',
params=params,
headers={'X-API-Key': os.getenv('BYUL_API_KEY')},
timeout=30
)
if response.status_code == 200:
return response.json()
else:
error_data = response.json()
logger.error(f"API Error {response.status_code}: {error_data.get('message')}")
return None
except requests.exceptions.Timeout:
logger.error("Request timeout")
return None
except requests.exceptions.RequestException as e:
logger.error(f"Request failed: {e}")
return None
# Usage
news = safe_get_news({'symbol': 'AAPL'})
if news:
print(f"Found {len(news['items'])} AAPL articles")
```
## Flask Integration
### News API Server
```python
from flask import Flask, request, jsonify
import requests
import os
from functools import wraps
import time
app = Flask(__name__)
class RateLimiter:
def __init__(self):
self.requests = {}
def is_allowed(self, key: str, limit: int = 100, window: int = 3600) -> bool:
now = time.time()
if key not in self.requests:
self.requests[key] = []
# Remove old requests outside the window
self.requests[key] = [req_time for req_time in self.requests[key]
if now - req_time < window]
if len(self.requests[key]) < limit:
self.requests[key].append(now)
return True
return False
rate_limiter = RateLimiter()
def rate_limit(f):
@wraps(f)
def decorated_function(*args, **kwargs):
client_ip = request.environ.get('REMOTE_ADDR')
if not rate_limiter.is_allowed(client_ip):
return jsonify({'error': 'Rate limit exceeded'}), 429
return f(*args, **kwargs)
return decorated_function
@app.route('/api/news')
@rate_limit
def get_news_api():
"""Proxy endpoint for Byul news API"""
# Validate parameters
try:
limit = int(request.args.get('limit', 10))
min_importance = int(request.args.get('minImportance', 1))
if not (1 <= limit <= 100):
return jsonify({'error': 'limit must be between 1 and 100'}), 400
if not (1 <= min_importance <= 10):
return jsonify({'error': 'minImportance must be between 1 and 10'}), 400
except ValueError:
return jsonify({'error': 'Invalid parameter format'}), 400
# Build parameters
params = {'limit': limit, 'minImportance': min_importance}
if request.args.get('symbol'):
params['symbol'] = request.args.get('symbol')
if request.args.get('q'):
params['q'] = request.args.get('q')
try:
response = requests.get(
'https://api.byul.ai/api/v2/news',
params=params,
headers={'X-API-Key': os.getenv('BYUL_API_KEY')},
timeout=30
)
if response.status_code == 200:
return jsonify(response.json())
else:
return jsonify(response.json()), response.status_code
except requests.exceptions.RequestException as e:
return jsonify({'error': 'External API error'}), 503
@app.route('/health')
def health_check():
"""Health check endpoint"""
try:
response = requests.get(
'https://api.byul.ai/api/v2/news/health',
timeout=10
)
return jsonify(response.json()), response.status_code
except requests.exceptions.RequestException:
return jsonify({'status': 'unhealthy'}), 503
if __name__ == '__main__':
app.run(debug=True, port=5000)
```
## Advanced Examples
### News Client Class
```python
import requests
import os
import time
from typing import Dict, List, Optional, Generator
from dataclasses import dataclass
import logging
@dataclass
class NewsArticle:
id: str
title: str
url: str
date: str
importance_score: int
category: str
symbols: List[str]
sentiment: Optional[str] = None
class ByulNewsClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.byul.ai/api/v2"
self.session = requests.Session()
self.session.headers.update({'X-API-Key': api_key})
# Setup logging
self.logger = logging.getLogger(__name__)
def _make_request(self, endpoint: str, params: Dict = None) -> Dict:
"""Make API request with error handling"""
url = f"{self.base_url}{endpoint}"
try:
response = self.session.get(url, params=params, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
error_data = response.json() if response.content else {}
raise Exception(f"API Error {response.status_code}: {error_data.get('message', str(e))}")
def get_news(self, **filters) -> Dict:
"""Get news with optional filters"""
return self._make_request('/news', filters)
def get_health(self) -> Dict:
"""Check API health"""
return self._make_request('/news/health')
def get_all_news(self, **filters) -> List[Dict]:
"""Get all available news with pagination"""
all_news = []
cursor = None
while True:
params = {**filters, 'limit': 100}
if cursor:
params['cursor'] = cursor
data = self.get_news(**params)
all_news.extend(data['items'])
if not data.get('hasMore'):
break
cursor = data.get('nextCursor')
# Safety check
if len(all_news) > 10000:
self.logger.warning("Retrieved over 10k articles, stopping pagination")
break
return all_news
def get_portfolio_news(self, symbols: List[str], min_importance: int = 6) -> List[Dict]:
"""Get news for multiple symbols"""
all_news = {}
for symbol in symbols:
try:
data = self.get_news(symbol=symbol, minImportance=min_importance, limit=50)
for article in data['items']:
all_news[article['_id']] = article
except Exception as e:
self.logger.error(f"Failed to fetch news for {symbol}: {e}")
# Sort by importance
return sorted(all_news.values(),
key=lambda x: x['importanceScore'],
reverse=True)
def stream_news(self, **filters) -> Generator[Dict, None, None]:
"""Stream news articles as they become available"""
last_article_id = None
while True:
try:
params = {**filters, 'limit': 50}
if last_article_id:
params['sinceId'] = last_article_id
data = self.get_news(**params)
if data['items']:
last_article_id = data['items'][0]['_id']
for article in data['items']:
yield article
# Wait before next poll
time.sleep(30)
except KeyboardInterrupt:
break
except Exception as e:
self.logger.error(f"Streaming error: {e}")
time.sleep(60) # Wait longer on errors
# Usage examples
client = ByulNewsClient(os.getenv('BYUL_API_KEY'))
# Get breaking news
breaking_news = client.get_news(minImportance=9)
print(f"Breaking news: {len(breaking_news['items'])} articles")
# Get portfolio news
portfolio = client.get_portfolio_news(['AAPL', 'GOOGL', 'MSFT'])
print(f"Portfolio news: {len(portfolio)} articles")
# Stream news (run in separate thread/process)
# for article in client.stream_news(minImportance=7):
# print(f"New article: {article['title']}")
```
### Data Analysis with Pandas
```python
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
class NewsAnalyzer:
def __init__(self, client: ByulNewsClient):
self.client = client
def get_news_dataframe(self, days: int = 7, **filters) -> pd.DataFrame:
"""Get news as pandas DataFrame"""
# Get all news from the past week
news = self.client.get_all_news(**filters)
# Filter by date
cutoff_date = datetime.now() - timedelta(days=days)
# Convert to DataFrame
df = pd.DataFrame(news)
df['date'] = pd.to_datetime(df['date'])
df = df[df['date'] >= cutoff_date]
# Add derived columns
df['hour'] = df['date'].dt.hour
df['day_of_week'] = df['date'].dt.day_name()
df['has_symbols'] = df['symbols'].apply(lambda x: len(x) > 0 if x else False)
return df
def analyze_importance_distribution(self, df: pd.DataFrame) -> Dict:
"""Analyze importance score distribution"""
analysis = {
'mean_importance': df['importanceScore'].mean(),
'median_importance': df['importanceScore'].median(),
'breaking_news_count': len(df[df['importanceScore'] >= 9]),
'high_impact_count': len(df[df['importanceScore'] >= 7]),
'distribution': df['importanceScore'].value_counts().sort_index().to_dict()
}
return analysis
def analyze_by_category(self, df: pd.DataFrame) -> pd.DataFrame:
"""Analyze news by category"""
return df.groupby('category').agg({
'importanceScore': ['count', 'mean', 'max'],
'sentiment': lambda x: x.value_counts().to_dict() if x.notna().any() else {}
}).round(2)
def plot_news_timeline(self, df: pd.DataFrame, save_path: str = None):
"""Plot news timeline"""
plt.figure(figsize=(12, 6))
# Group by hour and importance
hourly_data = df.groupby([df['date'].dt.floor('H'), 'importanceScore']).size().unstack(fill_value=0)
# Plot stacked area chart
hourly_data.plot(kind='area', stacked=True, alpha=0.7, colormap='viridis')
plt.title('News Volume by Hour and Importance Score')
plt.xlabel('Time')
plt.ylabel('Number of Articles')
plt.legend(title='Importance Score', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
if save_path:
plt.savefig(save_path)
plt.show()
def find_trending_symbols(self, df: pd.DataFrame, min_mentions: int = 3) -> pd.DataFrame:
"""Find trending stock symbols"""
# Flatten symbols
symbol_rows = []
for _, row in df.iterrows():
if row['symbols']:
for symbol in row['symbols']:
symbol_rows.append({
'symbol': symbol,
'importance': row['importanceScore'],
'date': row['date'],
'sentiment': row['sentiment']
})
if not symbol_rows:
return pd.DataFrame()
symbol_df = pd.DataFrame(symbol_rows)
# Analyze by symbol
trending = symbol_df.groupby('symbol').agg({
'importance': ['count', 'mean', 'max'],
'sentiment': lambda x: x.mode().iloc[0] if len(x.mode()) > 0 else 'neutral'
}).round(2)
# Filter by minimum mentions
trending = trending[trending[('importance', 'count')] >= min_mentions]
# Sort by average importance
trending = trending.sort_values(('importance', 'mean'), ascending=False)
return trending
# Usage example
analyzer = NewsAnalyzer(client)
# Get news data for analysis
df = analyzer.get_news_dataframe(days=7, minImportance=5)
print(f"Analyzing {len(df)} articles from the past week")
# Analyze importance distribution
importance_analysis = analyzer.analyze_importance_distribution(df)
print("Importance Analysis:", importance_analysis)
# Analyze by category
category_analysis = analyzer.analyze_by_category(df)
print("Category Analysis:")
print(category_analysis)
# Find trending symbols
trending = analyzer.find_trending_symbols(df)
print("Trending Symbols:")
print(trending.head(10))
# Plot timeline
# analyzer.plot_news_timeline(df, 'news_timeline.png')
```
## Environment Setup
### requirements.txt
```txt
requests>=2.28.0
flask>=2.2.0
pandas>=1.5.0
matplotlib>=3.6.0
seaborn>=0.12.0
python-dotenv>=0.19.0
```
### Installation and Setup
```bash
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Set environment variable
export BYUL_API_KEY=byul_api_key
# Run the application
python app.py
```
### Using python-dotenv
```python
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
api_key = os.getenv('BYUL_API_KEY')
```
Create `.env` file:
```bash
BYUL_API_KEY=byul_api_key
FLASK_ENV=development
DEBUG=True
```
## Testing
### Unit Tests with pytest
```python
# test_byul_client.py
import pytest
import requests_mock
from byul_client import ByulNewsClient
@pytest.fixture
def client():
return ByulNewsClient('test_api_key')
@pytest.fixture
def mock_news_response():
return {
'items': [
{
'_id': '123',
'title': 'Test News',
'importanceScore': 8,
'date': '2024-01-15T10:30:00.000Z',
'category': 'earnings',
'symbols': ['AAPL']
}
],
'hasMore': False,
'nextCursor': None
}
def test_get_news_success(client, mock_news_response):
with requests_mock.Mocker() as m:
m.get(
'https://api.byul.ai/api/v2/news',
json=mock_news_response
)
result = client.get_news(limit=10)
assert result == mock_news_response
assert len(result['items']) == 1
assert result['items'][0]['title'] == 'Test News'
def test_get_news_api_error(client):
with requests_mock.Mocker() as m:
m.get(
'https://api.byul.ai/api/v2/news',
status_code=401,
json={'message': 'Unauthorized'}
)
with pytest.raises(Exception, match='API Error 401: Unauthorized'):
client.get_news()
def test_get_portfolio_news(client, mock_news_response):
with requests_mock.Mocker() as m:
# Mock multiple symbol requests
for symbol in ['AAPL', 'GOOGL']:
m.get(
f'https://api.byul.ai/api/v2/news?symbol={symbol}&minImportance=6&limit=50',
json=mock_news_response
)
result = client.get_portfolio_news(['AAPL', 'GOOGL'])
assert len(result) == 1 # Deduplicated
assert result[0]['_id'] == '123'
```
### Run Tests
```bash
# Install pytest
pip install pytest pytest-mock requests-mock
# Run tests
pytest test_byul_client.py -v
# Run with coverage
pip install pytest-cov
pytest test_byul_client.py --cov=byul_client --cov-report=html
```
# React
Source: https://docs.byul.ai/rest-api/examples/react
Complete React examples with backend proxy patterns
## Important Security Note
**Never use API keys directly in React**. API keys will be exposed to all website visitors in the browser. Always use a backend proxy.
## Recommended Architecture
### Insecure Pattern (Don't do this)
```javascript
// This exposes your API key to everyone
const apiKey = 'byul_api_key';
fetch('https://api.byul.ai/api/v2/news', {
headers: { 'X-API-Key': apiKey } // Not recommended: Exposed in browser
});
```
### Secure Pattern (Recommended)
```javascript
// React calls your backend, backend calls Byul API
fetch('/api/news') // Recommended: Your backend handles API key
```
## Backend Proxy Setup
First, create a backend API that proxies requests to Byul:
### Node.js/Express Backend
```javascript
// server/server.js
const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// Proxy endpoint
app.get('/api/news', async (req, res) => {
try {
const { limit, minImportance, symbol, q, startDate, endDate } = req.query;
const params = new URLSearchParams({
limit: limit || '20',
minImportance: minImportance || '6'
});
if (symbol) params.append('symbol', symbol);
if (q) params.append('q', q);
if (startDate) params.append('startDate', startDate);
if (endDate) params.append('endDate', endDate);
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
if (!response.ok) {
return res.status(response.status).json({ error: 'API request failed' });
}
const data = await response.json();
res.json(data);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(3001, () => {
console.log('Proxy server running on port 3001');
});
```
## React Examples
### Basic News Component
```jsx
import React, { useState, useEffect } from 'react';
function NewsComponent() {
const [news, setNews] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchNews();
}, []);
const fetchNews = async () => {
try {
setLoading(true);
// Call your backend, not Byul API directly
const response = await fetch('/api/news?limit=10&minImportance=7&startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setNews(data.items);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
if (loading) return Loading news...
;
if (error) return Error: {error}
;
return (
Financial News
{news.map(article => (
Importance: {article.importanceScore}/10 |
Category: {article.category} |
{article.symbols && article.symbols.length > 0 && (
Symbols: {article.symbols.join(', ')}
)}
{new Date(article.date).toLocaleString()}
))}
);
}
export default NewsComponent;
```
### News Hook with Filtering
```jsx
import { useState, useEffect } from 'react';
function useNews(filters = {}) {
const [news, setNews] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchNews = async (newFilters = {}) => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
limit: '20',
minImportance: '6',
...filters,
...newFilters
});
const response = await fetch(`/api/news?${params}`);
if (!response.ok) {
throw new Error(`Failed to fetch news: ${response.status}`);
}
const data = await response.json();
setNews(data.items);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchNews();
}, []);
return {
news,
loading,
error,
refetch: fetchNews
};
}
// Usage
function NewsApp() {
const { news, loading, error, refetch } = useNews();
const [symbol, setSymbol] = useState('');
const handleSymbolFilter = (e) => {
e.preventDefault();
refetch({ symbol });
};
return (
{loading &&
Loading...
}
{error &&
Error: {error}
}
{news.map(article => (
{article.title}
Importance: {article.importanceScore}/10
))}
);
}
```
### Real-time News Dashboard
```jsx
import React, { useState, useEffect, useRef } from 'react';
function NewsDashboard() {
const [articles, setArticles] = useState([]);
const [connected, setConnected] = useState(false);
const [error, setError] = useState(null);
const intervalRef = useRef(null);
useEffect(() => {
startPolling();
return () => stopPolling();
}, []);
const startPolling = () => {
setConnected(true);
// Fetch immediately
fetchLatestNews();
// Then poll every 30 seconds
intervalRef.current = setInterval(fetchLatestNews, 30000);
};
const stopPolling = () => {
setConnected(false);
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
};
const fetchLatestNews = async () => {
try {
const response = await fetch('/api/news?limit=10&minImportance=7');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Update articles, avoiding duplicates
setArticles(prevArticles => {
const existingIds = new Set(prevArticles.map(a => a._id));
const newArticles = data.items.filter(a => !existingIds.has(a._id));
return [...newArticles, ...prevArticles].slice(0, 50); // Keep latest 50
});
setError(null);
} catch (err) {
setError(err.message);
setConnected(false);
}
};
return (
{error && (
Error: {error}
Retry
)}
{articles.map(article => (
{article.importanceScore}/10
{article.category}
{article.symbols && article.symbols.length > 0 && (
{article.symbols.map(symbol => (
{symbol}
))}
)}
{new Date(article.date).toLocaleString()}
{article.sentiment && (
{article.sentiment}
)}
))}
{articles.length === 0 && !error && (
{connected ? 'Waiting for news updates...' : 'Not connected'}
)}
);
}
export default NewsDashboard;
```
### Portfolio News Tracker
```jsx
import React, { useState, useEffect } from 'react';
function PortfolioTracker() {
const [portfolio, setPortfolio] = useState(['AAPL', 'GOOGL', 'MSFT']);
const [news, setNews] = useState([]);
const [newSymbol, setNewSymbol] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
if (portfolio.length > 0) {
fetchPortfolioNews();
}
}, [portfolio]);
const fetchPortfolioNews = async () => {
setLoading(true);
try {
// Fetch news for each symbol in parallel
const promises = portfolio.map(symbol =>
fetch(`/api/news?symbol=${symbol}&minImportance=6&limit=20`)
.then(res => res.json())
);
const results = await Promise.all(promises);
// Combine and deduplicate
const allNews = [];
const seenIds = new Set();
results.forEach(data => {
data.items?.forEach(article => {
if (!seenIds.has(article._id)) {
allNews.push(article);
seenIds.add(article._id);
}
});
});
// Sort by importance and date
allNews.sort((a, b) => {
if (b.importanceScore !== a.importanceScore) {
return b.importanceScore - a.importanceScore;
}
return new Date(b.date) - new Date(a.date);
});
setNews(allNews);
} catch (error) {
console.error('Failed to fetch portfolio news:', error);
} finally {
setLoading(false);
}
};
const addSymbol = (e) => {
e.preventDefault();
const symbol = newSymbol.trim().toUpperCase();
if (symbol && !portfolio.includes(symbol)) {
setPortfolio(prev => [...prev, symbol]);
setNewSymbol('');
}
};
const removeSymbol = (symbolToRemove) => {
setPortfolio(prev => prev.filter(s => s !== symbolToRemove));
};
return (
Portfolio News Tracker
Portfolio ({portfolio.length} symbols)
{portfolio.map(symbol => (
{symbol}
removeSymbol(symbol)}
className="remove-btn"
>
×
))}
Portfolio News ({news.length} articles)
{loading ? 'Loading...' : 'Refresh'}
{loading &&
Loading portfolio news...
}
{news.map(article => (
{article.symbols?.join(', ') || 'General'}
Importance: {article.importanceScore}/10
{article.category}
{new Date(article.date).toLocaleDateString()}
))}
);
}
export default PortfolioTracker;
```
## Next.js Integration
### API Route (Next.js 13+ App Router)
```javascript
// app/api/news/route.js
import { NextResponse } from 'next/server';
export async function GET(request) {
const { searchParams } = new URL(request.url);
const limit = searchParams.get('limit') || '20';
const minImportance = searchParams.get('minImportance') || '6';
const symbol = searchParams.get('symbol');
const q = searchParams.get('q');
try {
const params = new URLSearchParams({ limit, minImportance });
if (symbol) params.append('symbol', symbol);
if (q) params.append('q', q);
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: {
'X-API-Key': process.env.BYUL_API_KEY
},
// Next.js caching
next: { revalidate: 300 } // 5 minutes
});
if (!response.ok) {
return NextResponse.json(
{ error: 'Failed to fetch news' },
{ status: response.status }
);
}
const data = await response.json();
return NextResponse.json(data);
} catch (error) {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
### React Server Component (Next.js 13+)
```jsx
// app/news/page.js
async function getNews() {
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/news`, {
next: { revalidate: 300 } // 5 minute cache
});
if (!response.ok) {
throw new Error('Failed to fetch news');
}
return response.json();
}
export default async function NewsPage() {
const newsData = await getNews();
return (
Latest Financial News
{newsData.items.map(article => (
{article.title}
Importance: {article.importanceScore}/10
Read more
))}
);
}
```
## Environment Setup
### Create React App
```bash
# Install dependencies
npm install
# Create .env.local file
echo "REACT_APP_API_URL=http://localhost:3001" > .env.local
# Start development server
npm start
```
### Next.js
```bash
# Create .env.local file
echo "BYUL_API_KEY=byul_api_key" > .env.local
echo "NEXT_PUBLIC_API_URL=http://localhost:3000" >> .env.local
# Start development server
npm run dev
```
### Testing
```bash
# Test backend proxy
curl http://localhost:3001/api/news
# Test React app
npm test
# Check for security issues
npm audit
```
### Production Deployment
**Environment Variables:**
```bash
# Backend server
BYUL_API_KEY=byul_api_key
# Frontend (if needed for API URL)
REACT_APP_API_URL=https://your-backend-api.com
```
**Security Checklist:**
* API key only in backend environment
* CORS properly configured
* Rate limiting on proxy endpoints
* Input validation on all parameters
* Error messages don't expose internal details
## CSS Styling Example
```css
.news-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.news-item {
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
margin-bottom: 16px;
background: white;
}
.news-item h3 {
margin: 0 0 8px 0;
}
.news-item h3 a {
color: #2563eb;
text-decoration: none;
}
.news-item h3 a:hover {
text-decoration: underline;
}
.importance-badge {
background: #f3f4f6;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.875rem;
font-weight: 500;
}
.symbol-tag {
background: #3b82f6;
color: white;
padding: 2px 6px;
border-radius: 4px;
font-size: 0.75rem;
margin-right: 4px;
}
.status.connected {
color: #059669;
}
.status.disconnected {
color: #dc2626;
}
.sentiment.positive {
color: #059669;
}
.sentiment.negative {
color: #dc2626;
}
.sentiment.neutral {
color: #6b7280;
}
```
# Data Format
Source: https://docs.byul.ai/rest-api/news/data-format
News article data structure and field descriptions
## Response Structure
The REST API returns news data in a paginated format with the following structure:
```json
{
"items": [
// Array of news articles
],
"nextCursor": "67850d7b0123456789abcde0",
"hasMore": true
}
```
### Top-Level Fields
**`items`** (array)\
Array of news article objects
**`nextCursor`** (string, nullable)\
Pagination cursor for the next page. Only present when `hasMore` is `true`
**`hasMore`** (boolean)\
Whether additional pages are available
## Example API Calls
### Get Recent News Articles
Get the latest 5 articles to see the data format:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=5" \
-H "X-API-Key: byul_api_key"
```
### Get High-Quality Articles Only
Filter for articles with importance score 7+ to see richer data:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=3&minImportance=7" \
-H "X-API-Key: byul_api_key"
```
### Test Pagination
Get first page, then use cursor for next page:
```bash
# First page
curl -X GET "https://api.byul.ai/api/v2/news?limit=2" \
-H "X-API-Key: byul_api_key"
# Next page (use nextCursor from response)
curl -X GET "https://api.byul.ai/api/v2/news?limit=2&cursor=YOUR_CURSOR_HERE" \
-H "X-API-Key: byul_api_key"
```
## News Article Structure
Each article in the `items` array follows this structure based on the official API:
```json
{
"_id": "67850d7b0123456789abcdef",
"title": "Tesla Stock Surges After Q4 Earnings Beat",
"koTitle": "테슬라 4분기 실적 발표 후 주가 급등",
"content": "Tesla Inc. reported stronger-than-expected Q4 2024 earnings, with revenue beating analyst estimates by 8%. The electric vehicle maker delivered 484,507 vehicles in Q4, up 15% year-over-year, driving shares up 12% in after-hours trading.",
"koContent": "테슬라가 2024년 4분기 실적에서 애널리스트 예상치를 8% 상회하는 매출을 기록했습니다. 이 전기차 제조업체는 4분기에 484,507대를 인도하며 전년 대비 15% 증가했고, 시간외 거래에서 주가가 12% 상승했습니다.",
"url": "https://www.byul.ai/news/tesla-earnings-q4-2024",
"date": "2024-01-15T10:30:00.000Z",
"source": "byul.ai",
"timestamp": 1705401000,
"importanceScore": 8,
"category": "earnings",
"symbols": ["TSLA"],
"sentiment": "positive"
}
```
## Field Descriptions
### Core Identifiers
**`_id`** (string, required)\
Unique article identifier. Use this for deduplication and referencing.
**`title`** (string, required)\
Primary article headline, usually in English
**`koTitle`** (string, optional)\
Korean translation of the title
### Content & Source
**`url`** (string, required)\
Link to the original article on byul.ai
**`source`** (string, required)\
News source identifier. Always returns `"byul.ai"`
**`content`** (string, optional)\
Full or summarized article content when available. This field may be omitted for some news items.
**`koContent`** (string, optional)\
Korean content or summary when available. This field may be omitted for some news items.
### Timestamps
**`date`** (string, required)\
Article publication date in ISO 8601 format (UTC)
**`timestamp`** (integer, required)\
Unix timestamp of the article date
You can filter by date range using `startDate` and/or `endDate` query parameters. Both must be ISO 8601 UTC timestamps. When both are provided, `startDate` must be less than or equal to `endDate`.
### Market Data
**`importanceScore`** (integer, required)\
Market importance score from 0-10, where:
* **0-3**: Low impact
* **4-6**: Medium impact
* **7-8**: High impact
* **9-10**: Breaking news / Major market events
**`category`** (string, required)\
News category classification:
* `"earnings"` - Earnings reports and financial results
* `"fed"` - Federal Reserve and central bank news
* `"global"` - General economic and market news
* `"crypto"` - Cryptocurrency and blockchain news
* `"markets"` - Stock market and trading news
**`symbols`** (array of strings, optional)\
Related stock symbols. May be empty array `[]` for general news.
**`sentiment`** (string, optional)\
Sentiment analysis result:
* `"positive"` - Bullish/positive market impact
* `"negative"` - Bearish/negative market impact
* `"neutral"` - No clear directional impact
## Data Types and Validation
### Field Types
| Field | Type | Required | Format | Validation |
| ----------------- | ------- | -------- | ---------------- | -------------------------------------------------------------- |
| `_id` | string | Yes | MongoDB ObjectId | 24 hex characters |
| `title` | string | Yes | Text | Max 500 characters |
| `koTitle` | string | No | Text | Max 500 characters |
| `content` | string | No | Text | May be omitted; when present, contains article content/summary |
| `koContent` | string | No | Text | May be omitted; Korean content/summary when available |
| `url` | string | Yes | URL | Valid HTTPS URL |
| `date` | string | Yes | ISO 8601 | UTC timezone |
| `source` | string | Yes | Text | Always "byul.ai" |
| `timestamp` | integer | Yes | Unix timestamp | Positive integer |
| `importanceScore` | integer | Yes | Number | 0-10 range |
| `category` | string | Yes | Enum | See categories above |
| `symbols` | array | No | String array | Stock symbols |
| `sentiment` | string | No | Enum | positive/negative/neutral |
### Example Validation
```javascript
const validateArticle = (article) => {
// Required fields
if (!article._id || typeof article._id !== 'string') {
throw new Error('Invalid _id');
}
// Importance score validation
if (!Number.isInteger(article.importanceScore) ||
article.importanceScore < 0 ||
article.importanceScore > 10) {
throw new Error('importanceScore must be integer 0-10');
}
// Date validation
if (!article.date || isNaN(new Date(article.date).getTime())) {
throw new Error('Invalid date format');
}
// Sentiment validation (if present)
if (article.sentiment &&
!['positive', 'negative', 'neutral'].includes(article.sentiment)) {
throw new Error('Invalid sentiment value');
}
return true;
};
```
## Working with the Data
### Extracting Key Information
```javascript
const processNews = (response) => {
return response.items.map(article => ({
id: article._id,
headline: article.title,
publishedAt: new Date(article.date),
importance: article.importanceScore,
isBreaking: article.importanceScore >= 9,
affectedStocks: article.symbols || [],
marketSentiment: article.sentiment,
readMoreUrl: article.url
}));
};
```
### Filtering High-Impact News
```javascript
const getHighImpactNews = (response) => {
return response.items.filter(article =>
article.importanceScore >= 7
);
};
```
### Grouping by Category
```javascript
const groupByCategory = (response) => {
return response.items.reduce((groups, article) => {
const category = article.category;
groups[category] = groups[category] || [];
groups[category].push(article);
return groups;
}, {});
};
```
### Symbol-Specific News
```javascript
const getSymbolNews = (response, targetSymbol) => {
return response.items.filter(article =>
article.symbols &&
article.symbols.includes(targetSymbol)
);
};
```
## Pagination Handling
```javascript
const getAllNews = async (filters = {}) => {
let allArticles = [];
let cursor = null;
let hasMore = true;
while (hasMore) {
const params = new URLSearchParams({
limit: '100',
...filters,
...(cursor && { cursor })
});
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
const data = await response.json();
allArticles.push(...data.items);
cursor = data.nextCursor;
hasMore = data.hasMore;
// Prevent infinite loops
if (allArticles.length > 10000) break;
}
return allArticles;
};
```
## Data Consistency
The news article structure is identical between REST API and WebSocket responses, ensuring consistent data handling across both interfaces.
**Key consistency points:**
* Field names and types are identical
* `importanceScore` is always an integer (0-10)
* `sentiment` is always a string enum
* Timestamp formats are consistent (ISO 8601 for dates, Unix for timestamp)
* Symbol arrays use same format
This allows you to use the same data processing functions for both REST and WebSocket data sources.
# Filtering
Source: https://docs.byul.ai/rest-api/news/filtering
Filter news by importance, symbols, search queries, and more
## Query Parameters
The `/news` endpoint supports multiple filtering options to help you get exactly the news you need.
### Basic Filters
**`limit`** (integer, optional)\
Number of articles to return per request
* **Range**: 1-100
* **Default**: 10
* **Example**: `?limit=50`
**`minImportance`** (integer, optional)\
Minimum importance score for articles
* **Range**: 1-10
* **Default**: 1 (all articles)
* **Example**: `?minImportance=7` (high-impact news only)
### Search and Symbols
**`q`** (string, optional)\
Search query to filter articles by content
* **Format**: Free text search
* **Example**: `?q=tesla earnings`
* **Behavior**: Searches title and content
**`symbol`** (string, optional)\
Filter articles related to specific stock symbol
### Date Range
Filter articles within a specific time window using ISO 8601 timestamps:
**`startDate`** (string, optional)\
Start of the date range (inclusive)
* **Format**: ISO 8601 (UTC)
* **Example**: `?startDate=2024-01-01T00:00:00.000Z`
**`endDate`** (string, optional)\
End of the date range (inclusive)
* **Format**: ISO 8601 (UTC)
* **Example**: `?endDate=2024-01-31T23:59:59.999Z`
If both `startDate` and `endDate` are provided, `startDate` must be less than or equal to `endDate`.
* **Format**: Stock symbol (e.g., "AAPL", "TSLA")
* **Example**: `?symbol=AAPL`
* **Behavior**: Returns articles where the symbol appears in the `symbols` array
### Pagination
**`cursor`** (string, optional)\
Pagination cursor for retrieving next page
* **Source**: Use `nextCursor` from previous response
* **Example**: `?cursor=67850d7b0123456789abcde0`
**`sinceId`** (string, optional)\
Retrieve articles created after the specified article ID
* **Format**: Article ID (\_id field)
* **Example**: `?sinceId=67850d7b0123456789abcdef`
* **Use case**: Real-time polling for new articles
## Filtering Examples
### High-Impact News Only
Get only breaking news and major market events:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?minImportance=9" \
-H "X-API-Key: byul_api_key"
```
```javascript
const getBreakingNews = async () => {
const response = await fetch('https://api.byul.ai/api/v2/news?minImportance=9', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
const data = await response.json();
console.log(`Breaking: ${data.items.length} major news events`);
return data.items;
};
```
```python
def get_breaking_news():
response = requests.get(
'https://api.byul.ai/api/v2/news',
params={'minImportance': 9},
headers={'X-API-Key': os.getenv('BYUL_API_KEY')}
)
data = response.json()
print(f'Breaking: {len(data["items"])} major news events')
return data['items']
```
### Symbol-Specific News
Track news for specific stocks:
```javascript
const getTeslaNews = async () => {
const response = await fetch('https://api.byul.ai/api/v2/news?symbol=TSLA&limit=20', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
const data = await response.json();
return data.items;
};
```
### Search Query Filtering
### Date Range Filtering
Retrieve January articles only:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z" \
-H "X-API-Key: byul_api_key"
```
```javascript
const januaryNews = async () => {
const url = new URL('https://api.byul.ai/api/v2/news');
url.searchParams.set('startDate', '2024-01-01T00:00:00.000Z');
url.searchParams.set('endDate', '2024-01-31T23:59:59.999Z');
const res = await fetch(url, { headers: { 'X-API-Key': process.env.BYUL_API_KEY } });
return res.json();
};
```
```python
import requests, os
resp = requests.get(
'https://api.byul.ai/api/v2/news',
params={
'startDate': '2024-01-01T00:00:00.000Z',
'endDate': '2024-01-31T23:59:59.999Z'
},
headers={'X-API-Key': os.getenv('BYUL_API_KEY')}
)
data = resp.json()
```
Find articles about specific topics:
```javascript
const searchEarningsNews = async () => {
const response = await fetch('https://api.byul.ai/api/v2/news?q=earnings%20report&minImportance=5', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
const data = await response.json();
return data.items;
};
```
### Combining Multiple Filters
Get high-impact Apple news with search query:
```bash
curl -X GET "https://api.byul.ai/api/v2/news?symbol=AAPL&minImportance=7&q=earnings&limit=50&startDate=2024-01-01T00:00:00.000Z&endDate=2024-12-31T23:59:59.999Z" \
-H "X-API-Key: byul_api_key"
```
## Advanced Filtering Patterns
### Portfolio Tracking
Monitor news for multiple symbols:
```javascript
const getPortfolioNews = async (symbols) => {
const allNews = [];
// Make parallel requests for each symbol
const promises = symbols.map(symbol =>
fetch(`https://api.byul.ai/api/v2/news?symbol=${symbol}&minImportance=6&limit=20`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
}).then(res => res.json())
);
const results = await Promise.all(promises);
// Combine and deduplicate results
const newsMap = new Map();
results.forEach(data => {
data.items.forEach(article => {
newsMap.set(article._id, article);
});
});
return Array.from(newsMap.values())
.sort((a, b) => b.importanceScore - a.importanceScore);
};
// Usage
const portfolioNews = await getPortfolioNews(['AAPL', 'GOOGL', 'MSFT', 'TSLA']);
```
### Real-Time Polling
Poll for new articles since last check:
```javascript
class NewsPoller {
constructor(apiKey) {
this.apiKey = apiKey;
this.lastArticleId = null;
}
async pollForNewNews() {
const params = new URLSearchParams({
limit: '50',
minImportance: '6'
});
if (this.lastArticleId) {
params.append('sinceId', this.lastArticleId);
}
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: { 'X-API-Key': this.apiKey }
});
const data = await response.json();
if (data.items.length > 0) {
this.lastArticleId = data.items[0]._id;
console.log(`🆕 Found ${data.items.length} new articles`);
}
return data.items;
}
startPolling(intervalMs = 30000) {
return setInterval(() => {
this.pollForNewNews();
}, intervalMs);
}
}
```
### Importance-Based Filtering
Create different news feeds based on importance:
```javascript
const createNewsFeeds = async () => {
const [breaking, important, general] = await Promise.all([
// Breaking news (9-10)
fetch('https://api.byul.ai/api/v2/news?minImportance=9&limit=10', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
}).then(res => res.json()),
// Important news (7-8)
fetch('https://api.byul.ai/api/v2/news?minImportance=7&limit=20', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
}).then(res => res.json()),
// General news (4-6)
fetch('https://api.byul.ai/api/v2/news?minImportance=4&limit=30', {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
}).then(res => res.json())
]);
return {
breaking: breaking.items,
important: important.items,
general: general.items
};
};
```
## Filter Validation
Always validate filter parameters to avoid API errors:
```javascript
const validateFilters = (filters) => {
const errors = [];
if (filters.limit && (filters.limit < 1 || filters.limit > 100)) {
errors.push('limit must be between 1 and 100');
}
if (filters.minImportance && (filters.minImportance < 1 || filters.minImportance > 10)) {
errors.push('minImportance must be between 1 and 10');
}
if (filters.symbol && !/^[A-Z]{1,5}$/.test(filters.symbol)) {
errors.push('symbol must be 1-5 uppercase letters');
}
if (filters.q && filters.q.length > 100) {
errors.push('search query too long (max 100 characters)');
}
return errors;
};
const makeNewsRequest = async (filters) => {
const validationErrors = validateFilters(filters);
if (validationErrors.length > 0) {
throw new Error(`Invalid filters: ${validationErrors.join(', ')}`);
}
const params = new URLSearchParams(filters);
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
return response.json();
};
```
## Best Practices
### Efficient Filtering
1. **Use appropriate limits**: Don't request more data than you need
2. **Filter server-side**: Use API filters instead of client-side filtering
3. **Combine filters**: Use multiple parameters to narrow results
4. **Cache results**: Store filtered results to reduce API calls
### Rate Limit Optimization
```javascript
// Good: Single request with filters
const news = await fetch('https://api.byul.ai/api/v2/news?symbol=AAPL&minImportance=7');
// Bad: Multiple requests + client filtering
const allNews = await fetch('https://api.byul.ai/api/v2/news?limit=100');
const filteredNews = allNews.items.filter(article =>
article.symbols?.includes('AAPL') && article.importanceScore >= 7
);
```
### Error Handling
```javascript
const safeFilteredRequest = async (filters) => {
try {
const response = await makeNewsRequest(filters);
return response;
} catch (error) {
if (error.message.includes('Invalid filters')) {
console.error('Filter validation failed:', error.message);
// Return default request without filters
return makeNewsRequest({});
}
throw error;
}
};
```
## Filter Combinations Reference
| Use Case | Recommended Filters | Example |
| ------------------- | --------------------------------- | ---------------------------------------------------------------------- |
| Breaking News | `minImportance=9` | `?minImportance=9&limit=10` |
| Stock Specific | `symbol=SYMBOL&minImportance=6` | `?symbol=AAPL&minImportance=6` |
| Earnings Season | `q=earnings&minImportance=5` | `?q=earnings&minImportance=5` |
| Fed News | `q=fed&minImportance=7` | `?q=fed&minImportance=7` |
| Daily Digest | `minImportance=5&limit=50` | `?minImportance=5&limit=50` |
| Real-time Updates | `sinceId=LAST_ID&minImportance=6` | `?sinceId=67850...&minImportance=6` |
| Specific Date Range | `startDate&endDate` | `?startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z` |
# Overview
Source: https://docs.byul.ai/rest-api/overview
Byul REST API v2 reference documentation
## REST API
Byul REST API v2 provides access to financial news data through RESTful JSON endpoints.
**Base URL:** `https://api.byul.ai/api/v2`
## Features
* Financial news data access
* Importance scoring (1-10)
* Symbol-based filtering
* Cursor-based pagination
* Real-time updates
* Date range filtering (startDate/endDate)
## Authentication
Include your API key in the request header:
```http
X-API-Key: byul_api_key
```
## Quick Example
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=5&minImportance=8" \
-H "X-API-Key: byul_api_key"
```
```json
{
"items": [
{
"_id": "67850d7b0123456789abcdef",
"title": "Federal Reserve Raises Interest Rates by 0.25%",
"koTitle": "연준, 기준금리 0.25% 인상",
"content": "The Federal Open Market Committee (FOMC) announced a 0.25 percentage point increase in the federal funds rate, citing continued economic growth and persistent inflation concerns. This marks the sixth rate hike this cycle.",
"koContent": "연방공개시장위원회(FOMC)가 지속적인 경제 성장과 인플레이션 우려를 이유로 연방기금금리를 0.25%포인트 인상한다고 발표했습니다. 이는 현 사이클에서 여섯 번째 금리 인상입니다.",
"url": "https://www.byul.ai/news/fed-rate-decision-2024",
"date": "2024-01-15T14:00:00.000Z",
"importanceScore": 9,
"category": "central_banks",
"symbols": ["DXY", "SPY"],
"sentiment": "neutral"
}
],
"nextCursor": "67850d7b0123456789abcde0",
"hasMore": true
}
```
## Endpoints
### GET /news
Retrieve financial news articles.
**Parameters:**
* `limit` (integer): Articles to return (1-100, default: 20)
* `minImportance` (integer): Minimum importance score (1-10, default: 1)
* `symbol` (string): Filter by stock symbol
* `q` (string): Search query
* `cursor` (string): Pagination cursor
* `category` (string): News category filter
* `startDate` (string): Start of date range (ISO 8601)
* `endDate` (string): End of date range (ISO 8601)
## Rate Limits
| Plan | Rate Limit |
| ----------- | ------------------- |
| Test (Free) | 30 requests/minute |
| Starter | 60 requests/minute |
| Pro | 120 requests/minute |
| Enterprise | Custom |
**Headers:**
* `X-V2-RateLimit-Limit`
* `X-V2-RateLimit-Remaining`
* `X-V2-RateLimit-Used`
* `X-V2-RateLimit-Reset`
## Response Format
**Article Object:**
* `_id`: Unique article identifier
* `title`: Article title
* `url`: Source URL
* `date`: Publication date (ISO 8601)
* `importanceScore`: Market importance (1-10)
* `category`: News category
* `symbols`: Associated stock symbols (array)
* `sentiment`: Sentiment analysis result
* `content`: Article content or summary (optional; may be absent)
* `koContent`: Korean content or summary (optional; may be absent)
## Next Steps
Get started with REST API requests
Code examples in multiple languages
API key setup and security
Handle API errors and status codes
# Quickstart
Source: https://docs.byul.ai/rest-api/quickstart
Get up and running with Byul REST API in 5 minutes
## Get Started in 5 Minutes
### Prerequisites
REST API is available on all plans. See [pricing](https://www.byul.ai/api/pricing) for rate limits and features.
### Step 1: Get Your API Key
1. Login to [Byul API Dashboard](https://www.byul.ai/api/dashboard)
2. Your API key is automatically generated and displayed
3. Copy your API key (starts with `byul_v2`)
### Step 2: Make Your First Request
```bash
curl -X GET "https://api.byul.ai/api/v2/news?limit=10&minImportance=7&startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z" \
-H "X-API-Key: byul_api_key"
```
```javascript
const fetch = require('node-fetch');
const getNews = async () => {
const response = await fetch('https://api.byul.ai/api/v2/news?limit=10&minImportance=7&startDate=2024-01-01T00:00:00.000Z&endDate=2024-01-31T23:59:59.999Z', {
headers: {
'X-API-Key': process.env.BYUL_API_KEY
}
});
const data = await response.json();
console.log('Latest News:', data.items.length, 'articles');
data.items.forEach(article => {
console.log(`${article.title} - Importance: ${article.importanceScore}/10`);
});
return data;
};
getNews();
```
```python
import requests
import os
def get_news():
response = requests.get(
'https://api.byul.ai/api/v2/news',
params={
'limit': 10,
'minImportance': 7
},
headers={
'X-API-Key': os.getenv('BYUL_API_KEY')
}
)
if response.status_code == 200:
data = response.json()
print(f'Latest News: {len(data["items"])} articles')
for article in data['items']:
print(f"{article['title']} - Importance: {article['importanceScore']}/10")
return data
else:
print(f'Error: {response.status_code}')
return None
get_news()
```
### Step 3: Parse the Response
```json
{
"items": [
{
"_id": "67850d7b0123456789abcdef",
"title": "Tesla Stock Surges After Q4 Earnings Beat",
"koTitle": "테슬라 4분기 실적 상승으로 주가 급등",
"content": "Tesla Inc. reported stronger-than-expected Q4 2024 earnings, with revenue beating analyst estimates by 8%. The electric vehicle maker delivered 484,507 vehicles in Q4, up 15% year-over-year, driving shares up 12% in after-hours trading.",
"koContent": "테슬라가 2024년 4분기 실적에서 애널리스트 예상치를 8% 상회하는 매출을 기록했습니다. 이 전기차 제조업체는 4분기에 484,507대를 인도하며 전년 대비 15% 증가했고, 시간외 거래에서 주가가 12% 상승했습니다.",
"url": "https://www.byul.ai/news/tesla-earnings-q4-2024",
"date": "2024-01-15T10:30:00.000Z",
"importanceScore": 8,
"category": "earnings",
"symbols": ["TSLA"],
"sentiment": "positive"
}
],
"nextCursor": "67850d7b0123456789abcde0",
"hasMore": true
}
```
### Step 4: Handle Pagination
```javascript
const getAllNews = async () => {
let allNews = [];
let cursor = null;
let hasMore = true;
while (hasMore) {
const params = new URLSearchParams({
limit: '50',
minImportance: '6',
startDate: '2024-01-01T00:00:00.000Z'
});
if (cursor) {
params.append('cursor', cursor);
}
const response = await fetch(`https://api.byul.ai/api/v2/news?${params}`, {
headers: { 'X-API-Key': process.env.BYUL_API_KEY }
});
const data = await response.json();
allNews.push(...data.items);
cursor = data.nextCursor;
hasMore = data.hasMore;
}
console.log(`Retrieved ${allNews.length} total articles`);
return allNews;
};
```
## Congratulations!
You've successfully made your first REST API request and retrieved financial news!
### What's Next?
Learn about API key management and security
Filter news by importance, symbols, and categories
Understand the complete news article structure
Handle API errors and rate limits properly
## Troubleshooting
### Common Issues
**401 Unauthorized**
* Check your API key format (must start with `byul_`)
* Verify your API key at [Dashboard](https://www.byul.ai/api/dashboard)
* Ensure the X-API-Key header is set correctly
**429 Too Many Requests**
* You've exceeded your plan's rate limit
* Check rate limit headers in the response
* Implement exponential backoff retry logic
* Consider upgrading your plan at [Pricing](https://www.byul.ai/api/pricing)
**400 Bad Request**
* Check parameter values (limit: 1-100, minImportance: 1-10)
* Ensure proper URL encoding for query parameters
* Validate JSON structure if sending request body
### Need Help?
* Read the full [REST API Documentation](/rest-api/overview)
* Join our [Community](https://www.byul.ai/community)
* Contact [Support](https://www.byul.ai/contact)
**Pro Tip**: Use environment variables in production instead of hardcoding API keys:
```bash
export BYUL_API_KEY=byul_api_key
```
## Rate Limits by Plan
* **Test (Free)**: 30 requests/minute
* **Starter (\$19/month)**: 60 requests/minute
* **Pro (\$99/month)**: 120 requests/minute
* **Enterprise**: Custom limits
All responses include rate limit headers for monitoring usage.
# Authentication
Source: https://docs.byul.ai/websocket/authentication
Secure WebSocket authentication using API keys
# WebSocket Authentication
WebSocket connections require API key authentication for secure access to real-time news streams.
## Authentication Method
WebSocket authentication uses your API key provided during the connection handshake.
### API Key Setup
1. **Get Your API Key**
* Login to [Byul API Dashboard](https://www.byul.ai/api/dashboard)
* Your API key is displayed on the dashboard
* API keys start with `byul_v2_`
2. **Connection Authentication**
```javascript
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' }
});
```
## Authentication Flow
1. **Connection Request**: Client connects with API key in auth options
2. **Server Validation**: Server validates API key and plan permissions
3. **Authentication Success**: Server emits `auth:success` event with user details
4. **Ready for Subscriptions**: Client can now subscribe to news streams
### Authentication Success Event
```javascript
socket.on('auth:success', (data) => {
console.log('Authentication successful');
console.log('Plan:', data.user.plan);
console.log('Email:', data.user.email);
// Now safe to subscribe to news
socket.emit('news:subscribe', {
minImportance: 7,
startDate: '2024-01-01T00:00:00.000Z'
});
});
```
**Success Response Structure:**
```json
{
"message": "WebSocket authentication successful",
"user": {
"email": "user@example.com",
"plan": "pro"
}
}
```
## Error Handling
### Authentication Errors
```javascript
socket.on('news:error', (error) => {
console.error('Authentication failed:', error.message);
switch (error.code) {
case 'INVALID_API_KEY':
console.log('Please check your API key');
break;
case 'PLAN_REQUIRED':
console.log('WebSocket requires Pro or Enterprise plan');
break;
case 'RATE_LIMITED':
console.log('Too many connection attempts. Please wait.');
break;
}
});
```
**Common Error Codes:**
* `INVALID_API_KEY` - API key is invalid or malformed
* `PLAN_REQUIRED` - WebSocket access requires Pro/Enterprise plan
* `RATE_LIMITED` - Too many authentication attempts
* `CONNECTION_LIMIT` - Maximum connections exceeded for plan
## Security Best Practices
### Environment Variables
**Never hardcode API keys in your source code.** Use environment variables:
```javascript
// ✅ Good - Use environment variables
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
// ❌ Bad - Hardcoded API key
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' }
});
```
### Production Configuration
```javascript
// config/websocket.js
export const websocketConfig = {
url: process.env.WEBSOCKET_URL || 'wss://api.byul.ai/news-v2',
auth: {
apiKey: process.env.BYUL_API_KEY
},
// Additional security options
transports: ['websocket'], // Disable polling
upgrade: false,
rememberUpgrade: false
};
```
```jsx
// .env
REACT_APP_BYUL_API_KEY=byul_api_key
// src/config/websocket.js
export const websocketConfig = {
url: 'wss://api.byul.ai/news-v2',
auth: {
apiKey: process.env.REACT_APP_BYUL_API_KEY
}
};
```
```python
import os
from dotenv import load_dotenv
load_dotenv()
# config/settings.py
WEBSOCKET_CONFIG = {
'url': 'wss://api.byul.ai/news-v2',
'auth': {
'apiKey': os.getenv('BYUL_API_KEY')
}
}
```
### API Key Protection
**Backend Only**: Keep API keys on your backend servers. Never expose them to client-side JavaScript in production.
**Key Rotation**: Regularly rotate your API keys for enhanced security.
**Access Control**: Restrict API key access to authorized team members only.
## Connection Examples
### Basic Authentication
```javascript
import { io } from 'socket.io-client';
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
socket.on('connect', () => {
console.log('Connected to WebSocket');
});
socket.on('auth:success', (data) => {
console.log('Authenticated successfully:', data.user.plan);
});
socket.on('news:error', (error) => {
console.error('Authentication error:', error.message);
});
```
### With Reconnection
```javascript
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY },
// Reconnection settings
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000
});
socket.on('reconnect', (attemptNumber) => {
console.log(`Reconnected after ${attemptNumber} attempts`);
});
socket.on('reconnect_error', (error) => {
console.error('Reconnection failed:', error.message);
});
```
### Python Authentication
```python
import asyncio
import socketio
import os
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('Connected to WebSocket')
@sio.on('auth:success')
async def auth_success(data):
print(f"Authenticated successfully: {data['user']['plan']}")
# Subscribe to news after authentication
await sio.emit('news:subscribe', {
'minImportance': 7,
'startDate': '2024-01-01T00:00:00.000Z'
})
@sio.on('news:error')
async def auth_error(error):
print(f"Authentication error: {error['message']}")
async def main():
await sio.connect(
'wss://api.byul.ai/news-v2',
auth={'apiKey': os.getenv('BYUL_API_KEY')}
)
await sio.wait()
asyncio.run(main())
```
## Troubleshooting
### Authentication Issues
**Invalid API Key Format**
```
Error: API key must start with 'byul_v2_'
```
* Verify API key format from dashboard
* Check for extra whitespace or characters
**Plan Requirements**
```
Error: WebSocket streaming requires Pro or Enterprise plan
```
* [Upgrade your plan](https://www.byul.ai/api/pricing)
* Verify plan status in dashboard
**Connection Timeout**
```
Error: Authentication timeout
```
* Check network connectivity
* Verify firewall settings allow WebSocket connections
* Try connecting from a different network
### Testing Authentication
Test your authentication setup with a simple connection:
```javascript
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' },
timeout: 10000
});
socket.on('connect', () => {
console.log('✅ Connection successful');
});
socket.on('auth:success', (data) => {
console.log('✅ Authentication successful');
console.log('Plan:', data.user.plan);
socket.disconnect();
});
socket.on('news:error', (error) => {
console.log('❌ Authentication failed:', error.message);
socket.disconnect();
});
socket.on('connect_error', (error) => {
console.log('❌ Connection failed:', error.message);
});
```
## Next Steps
Subscribe to filtered news streams
Handle connection errors and implement retry logic
Advanced connection configuration and monitoring
Production-ready implementation examples
# Connection Guide
Source: https://docs.byul.ai/websocket/connection
Configure and manage stable WebSocket connections
## Advanced Connection Configuration
### Production-Ready Socket.IO Setup
```javascript
import { io } from 'socket.io-client';
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' },
// Production settings
transports: ['websocket'], // WebSocket only, no polling fallback
upgrade: true,
rememberUpgrade: true,
// Reconnection strategy
reconnection: true,
reconnectionAttempts: 10,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
maxReconnectionAttempts: 10,
randomizationFactor: 0.5,
// Timeout configuration
timeout: 20000,
// Performance options
forceNew: false,
multiplex: true
});
```
### Native WebSocket
```javascript
class ByulWebSocket {
constructor(apiKey) {
this.apiKey = apiKey;
this.url = 'wss://api.byul.ai/news-v2';
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 10;
this.reconnectDelay = 1000;
this.ws = null;
this.connect();
}
connect() {
try {
this.ws = new WebSocket(this.url, [], {
headers: {
'Authorization': `Bearer ${this.apiKey}`
}
});
this.setupEventListeners();
} catch (error) {
console.error('WebSocket connection failed:', error);
this.scheduleReconnect();
}
}
setupEventListeners() {
this.ws.onopen = () => {
console.log('WebSocket connected successfully');
this.reconnectAttempts = 0; // Reset reconnection counter
// Send authentication message
this.send('auth', { apiKey: this.apiKey });
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleMessage(data);
};
this.ws.onclose = (event) => {
console.log('WebSocket connection closed:', event.code, event.reason);
this.scheduleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
scheduleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
const delay = Math.min(
this.reconnectDelay * Math.pow(2, this.reconnectAttempts),
30000
);
console.log(`Reconnecting in ${delay}ms... (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`);
setTimeout(() => {
this.reconnectAttempts++;
this.connect();
}, delay);
} else {
console.error('Maximum reconnection attempts reached');
}
}
}
```
## Connection State Management
### Connection Status Tracking
```javascript
class ConnectionManager {
constructor() {
this.connectionState = 'disconnected'; // disconnected, connecting, connected, error
this.lastConnected = null;
this.connectionAttempts = 0;
}
updateState(newState) {
const oldState = this.connectionState;
this.connectionState = newState;
console.log(`Connection state changed: ${oldState} → ${newState}`);
// State-specific handling
switch (newState) {
case 'connected':
this.lastConnected = new Date();
this.connectionAttempts = 0;
this.onConnected();
break;
case 'disconnected':
this.onDisconnected();
break;
case 'error':
this.onError();
break;
}
}
onConnected() {
// UI updates, restart subscriptions, etc.
document.getElementById('connection-status').textContent = 'Connected';
document.getElementById('connection-indicator').className = 'connected';
}
onDisconnected() {
document.getElementById('connection-status').textContent = 'Disconnected';
document.getElementById('connection-indicator').className = 'disconnected';
}
onError() {
document.getElementById('connection-status').textContent = 'Connection Error';
document.getElementById('connection-indicator').className = 'error';
}
}
```
### Connection Quality Monitoring
```javascript
class ConnectionMonitor {
constructor(socket) {
this.socket = socket;
this.pingInterval = null;
this.lastPong = Date.now();
this.latency = 0;
this.startPingMonitoring();
}
startPingMonitoring() {
this.pingInterval = setInterval(() => {
const start = Date.now();
this.socket.emit('ping', start, (response) => {
this.latency = Date.now() - start;
this.lastPong = Date.now();
console.log(`Latency: ${this.latency}ms`);
this.updateConnectionQuality();
});
}, 30000); // Ping every 30 seconds
}
updateConnectionQuality() {
let quality = 'good';
if (this.latency > 1000) {
quality = 'poor';
} else if (this.latency > 500) {
quality = 'fair';
}
// Update UI
document.getElementById('connection-quality').textContent =
`Connection quality: ${quality} (${this.latency}ms)`;
}
checkConnection() {
const timeSinceLastPong = Date.now() - this.lastPong;
if (timeSinceLastPong > 60000) { // No response for over 1 minute
console.warn('Connection appears unstable. Attempting reconnection.');
this.socket.disconnect();
this.socket.connect();
}
}
destroy() {
if (this.pingInterval) {
clearInterval(this.pingInterval);
}
}
}
```
## Error Handling and Recovery
### Connection Error Handling
```javascript
socket.on('connect_error', (error) => {
console.error('Connection error:', error.message);
// Handle different error types
switch (error.type) {
case 'TransportError':
console.log('Please check your network connection');
break;
case 'AuthenticationError':
console.log('Please verify your API key');
// Show authentication error UI
showAuthenticationError();
break;
case 'RateLimitError':
console.log('Connection limit reached. Please try again later');
// Increase reconnection delay
increaseReconnectDelay();
break;
default:
console.log('Unknown connection error');
}
});
```
### Network Status Detection
```javascript
class NetworkMonitor {
constructor(socket) {
this.socket = socket;
this.isOnline = navigator.onLine;
window.addEventListener('online', () => {
console.log('Network connection restored');
this.isOnline = true;
if (!this.socket.connected) {
console.log('Attempting WebSocket reconnection');
this.socket.connect();
}
});
window.addEventListener('offline', () => {
console.log('Network connection lost');
this.isOnline = false;
});
}
checkNetworkStatus() {
if (!this.isOnline) {
console.log('Network is offline');
return false;
}
return true;
}
}
```
## Performance Optimization
### Connection Pooling
```javascript
class WebSocketPool {
constructor(maxConnections = 3) {
this.maxConnections = maxConnections;
this.connections = [];
this.currentConnectionIndex = 0;
}
createConnection(apiKey) {
if (this.connections.length >= this.maxConnections) {
// Reuse existing connection
return this.getNextConnection();
}
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey },
transports: ['websocket']
});
this.connections.push({
socket,
lastUsed: Date.now(),
subscriptions: new Set()
});
return socket;
}
getNextConnection() {
const connection = this.connections[this.currentConnectionIndex];
this.currentConnectionIndex = (this.currentConnectionIndex + 1) % this.connections.length;
connection.lastUsed = Date.now();
return connection.socket;
}
}
```
### Message Compression
```javascript
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY },
compression: true, // Enable message compression
perMessageDeflate: {
threshold: 1024, // Compress messages over 1KB only
concurrencyLimit: 10,
memLevel: 8
}
});
```
## Connection Termination and Cleanup
### Graceful Shutdown
```javascript
class GracefulShutdown {
constructor(socket) {
this.socket = socket;
this.isShuttingDown = false;
// Cleanup on page unload
window.addEventListener('beforeunload', () => {
this.shutdown();
});
// Handle process termination signals (Node.js)
process.on('SIGINT', () => {
this.shutdown();
});
}
async shutdown() {
if (this.isShuttingDown) return;
this.isShuttingDown = true;
console.log('Cleaning up WebSocket connections...');
try {
// Unsubscribe from all topics
this.socket.emit('news:unsubscribe:all');
// Wait for cleanup completion
await new Promise((resolve) => {
this.socket.on('unsubscribe:complete', resolve);
setTimeout(resolve, 1000); // Timeout fallback
});
// Close connection
this.socket.disconnect();
console.log('WebSocket connection closed gracefully');
} catch (error) {
console.error('Error during connection cleanup:', error);
}
}
}
```
## Best Practices
**Connection Configuration**
* Set appropriate timeout values (20-30 seconds)
* Implement exponential backoff for reconnection logic
* Limit maximum reconnection attempts
**Error Handling**
* Implement error handlers for all events
* Monitor network status
* Display user-friendly error messages
**Performance Optimization**
* Enable message compression
* Prevent unnecessary subscriptions
* Cache connection state
**Security**
* Secure API key management
* Use HTTPS/WSS only
* Validate connection authentication status
# Error Handling
Source: https://docs.byul.ai/websocket/error-handling
Comprehensive error handling and recovery strategies for WebSocket connections
## Error Types
### Connection Errors
Connection errors occur during the initial WebSocket handshake or due to network issues.
```javascript
socket.on('connect_error', (error) => {
console.error('Connection failed:', error.message);
switch (error.type) {
case 'TransportError':
handleTransportError(error);
break;
case 'timeout':
handleTimeoutError(error);
break;
case 'poll error':
handlePollError(error);
break;
default:
handleGenericError(error);
}
});
```
### Authentication Errors
Authentication errors occur during connection establishment.
For detailed authentication error codes and handling, see [Authentication Error Codes](/websocket/authentication#authentication-error-codes).
```javascript
socket.on('news:error', (error) => {
console.error('Authentication failed:', error.code);
// Handle specific authentication errors
// See authentication documentation for detailed handling
});
```
### Application-Level Errors
Application errors occur during WebSocket operations and data processing.
```javascript
socket.on('error', (error) => {
console.error('WebSocket error:', error);
switch (error.type) {
case 'ValidationError':
console.log('Data validation failed');
break;
case 'ProcessingError':
console.log('Server processing error');
break;
case 'TimeoutError':
console.log('Operation timeout');
break;
default:
console.log('Unknown application error');
}
});
```
## Error Handling Strategies
### Exponential Backoff
Implement exponential backoff to avoid overwhelming the server during reconnection attempts.
```javascript
class ExponentialBackoff {
constructor(initialDelay = 1000, maxDelay = 30000, factor = 2) {
this.initialDelay = initialDelay;
this.maxDelay = maxDelay;
this.factor = factor;
this.attempts = 0;
}
getDelay() {
const delay = Math.min(
this.initialDelay * Math.pow(this.factor, this.attempts),
this.maxDelay
);
this.attempts++;
return delay;
}
reset() {
this.attempts = 0;
}
}
// Usage
const backoff = new ExponentialBackoff();
socket.on('disconnect', () => {
const delay = backoff.getDelay();
console.log(`Reconnecting in ${delay}ms...`);
setTimeout(() => {
socket.connect();
}, delay);
});
socket.on('connect', () => {
backoff.reset(); // Reset on successful connection
});
```
### Circuit Breaker Pattern
Prevent cascading failures by implementing a circuit breaker pattern.
```javascript
class CircuitBreaker {
constructor(threshold = 5, timeout = 60000) {
this.failureThreshold = threshold;
this.timeout = timeout;
this.failureCount = 0;
this.lastFailureTime = null;
this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
}
canAttempt() {
if (this.state === 'CLOSED') {
return true;
}
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailureTime > this.timeout) {
this.state = 'HALF_OPEN';
return true;
}
return false;
}
if (this.state === 'HALF_OPEN') {
return true;
}
return false;
}
recordSuccess() {
this.failureCount = 0;
this.state = 'CLOSED';
}
recordFailure() {
this.failureCount++;
this.lastFailureTime = Date.now();
if (this.failureCount >= this.failureThreshold) {
this.state = 'OPEN';
}
}
}
// Usage
const circuitBreaker = new CircuitBreaker();
function attemptConnection() {
if (!circuitBreaker.canAttempt()) {
console.log('Circuit breaker is OPEN, skipping connection attempt');
return;
}
socket.connect();
}
socket.on('connect', () => {
circuitBreaker.recordSuccess();
});
socket.on('connect_error', () => {
circuitBreaker.recordFailure();
});
```
### Retry Logic
Implement intelligent retry logic with different strategies for different error types.
```javascript
class RetryManager {
constructor() {
this.maxRetries = {
'INVALID_API_KEY': 0, // Don't retry invalid API key
'PLAN_EXPIRED': 0, // Don't retry expired plan
'CONNECTION_LIMIT': 3, // Limited retries for connection limit
'NETWORK_ERROR': 10, // More retries for network issues
'DEFAULT': 5
};
this.retryCount = {};
}
shouldRetry(errorCode) {
const maxRetries = this.maxRetries[errorCode] || this.maxRetries.DEFAULT;
const currentRetries = this.retryCount[errorCode] || 0;
return currentRetries < maxRetries;
}
incrementRetry(errorCode) {
this.retryCount[errorCode] = (this.retryCount[errorCode] || 0) + 1;
}
resetRetries(errorCode = null) {
if (errorCode) {
this.retryCount[errorCode] = 0;
} else {
this.retryCount = {};
}
}
}
// Usage
const retryManager = new RetryManager();
socket.on('news:error', (error) => {
if (retryManager.shouldRetry(error.code)) {
retryManager.incrementRetry(error.code);
setTimeout(() => {
console.log(`Retrying connection (attempt ${retryManager.retryCount[error.code]})`);
socket.connect();
}, 5000);
} else {
console.error('Max retries reached for error:', error.code);
handleFinalError(error);
}
});
socket.on('connect', () => {
retryManager.resetRetries();
});
```
## Error Recovery
### Automatic Reconnection
Configure automatic reconnection with customizable parameters.
```javascript
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY },
// Reconnection configuration
reconnection: true,
reconnectionAttempts: 10,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
randomizationFactor: 0.5,
// Timeout configuration
timeout: 20000
});
// Handle reconnection events
socket.on('reconnect_attempt', (attemptNumber) => {
console.log(`Reconnection attempt #${attemptNumber}`);
});
socket.on('reconnect', (attemptNumber) => {
console.log(`Reconnected after ${attemptNumber} attempts`);
restoreSubscriptions();
});
socket.on('reconnect_error', (error) => {
console.error('Reconnection failed:', error);
});
socket.on('reconnect_failed', () => {
console.error('All reconnection attempts failed');
handleConnectionFailure();
});
```
### State Recovery
Restore application state after reconnection.
```javascript
class StateManager {
constructor() {
this.subscriptions = new Map();
this.connectionState = 'disconnected';
}
saveSubscription(id, params) {
this.subscriptions.set(id, params);
}
removeSubscription(id) {
this.subscriptions.delete(id);
}
restoreSubscriptions(socket) {
console.log(`Restoring ${this.subscriptions.size} subscriptions`);
for (const [id, params] of this.subscriptions) {
socket.emit('news:subscribe', params);
}
}
clearSubscriptions() {
this.subscriptions.clear();
}
}
// Usage
const stateManager = new StateManager();
// Save subscription when created
socket.emit('news:subscribe', { symbol: 'AAPL', startDate: '2024-01-01T00:00:00.000Z' });
stateManager.saveSubscription('aapl-news', { symbol: 'AAPL' });
// Restore on reconnection
socket.on('reconnect', () => {
stateManager.restoreSubscriptions(socket);
});
```
### Graceful Degradation
Implement fallback mechanisms when WebSocket connection fails.
```javascript
class FallbackManager {
constructor() {
this.fallbackActive = false;
this.pollInterval = null;
}
activateFallback() {
if (this.fallbackActive) return;
console.log('Activating fallback to REST API polling');
this.fallbackActive = true;
// Start polling REST API
this.pollInterval = setInterval(() => {
this.pollRestAPI();
}, 30000); // Poll every 30 seconds
}
deactivateFallback() {
if (!this.fallbackActive) return;
console.log('Deactivating fallback, WebSocket restored');
this.fallbackActive = false;
if (this.pollInterval) {
clearInterval(this.pollInterval);
this.pollInterval = null;
}
}
async pollRestAPI() {
try {
const response = await fetch('https://api.byul.ai/api/v2/news', {
headers: {
'X-API-Key': process.env.BYUL_API_KEY
}
});
const data = await response.json();
// Process data same as WebSocket
this.processNewsData(data.items);
} catch (error) {
console.error('Fallback REST API failed:', error);
}
}
processNewsData(articles) {
// Same processing logic as WebSocket data
articles.forEach(article => {
console.log(`News: ${article.title}`);
});
}
}
// Usage
const fallbackManager = new FallbackManager();
socket.on('disconnect', () => {
fallbackManager.activateFallback();
});
socket.on('connect', () => {
fallbackManager.deactivateFallback();
});
```
## User Experience
### Error Notifications
Provide clear error messages and recovery instructions to users.
```javascript
class ErrorNotificationManager {
constructor() {
this.notifications = new Map();
}
showError(type, message, actions = []) {
const notification = {
id: Date.now(),
type,
message,
actions,
timestamp: new Date()
};
this.notifications.set(notification.id, notification);
this.displayNotification(notification);
}
displayNotification(notification) {
const errorDiv = document.createElement('div');
errorDiv.className = `error-notification ${notification.type}`;
errorDiv.innerHTML = `
${notification.message}
${notification.actions.map(action =>
`${action.text} `
).join('')}
`;
document.getElementById('notifications').appendChild(errorDiv);
}
clearError(id) {
this.notifications.delete(id);
// Remove from DOM
const element = document.getElementById(`notification-${id}`);
if (element) {
element.remove();
}
}
}
// Usage
const errorNotifications = new ErrorNotificationManager();
socket.on('news:error', (error) => {
if (error.code === 'PLAN_EXPIRED') {
errorNotifications.showError('warning',
'Your subscription has expired. Please renew to continue using WebSocket features.',
[
{ text: 'Renew Subscription', handler: 'window.open("https://byul.ai/pricing")' },
{ text: 'Contact Support', handler: 'window.open("https://byul.ai/contact")' }
]
);
}
});
```
### Connection Status Indicator
Display real-time connection status to users.
```javascript
class ConnectionStatusIndicator {
constructor() {
this.statusElement = document.getElementById('connection-status');
this.indicatorElement = document.getElementById('connection-indicator');
}
updateStatus(status, message = '') {
const statusConfig = {
'connected': {
class: 'connected',
text: 'Connected',
color: '#10B981'
},
'connecting': {
class: 'connecting',
text: 'Connecting...',
color: '#F59E0B'
},
'disconnected': {
class: 'disconnected',
text: 'Disconnected',
color: '#EF4444'
},
'error': {
class: 'error',
text: 'Connection Error',
color: '#EF4444'
}
};
const config = statusConfig[status];
if (this.statusElement) {
this.statusElement.textContent = message || config.text;
this.statusElement.className = `status ${config.class}`;
}
if (this.indicatorElement) {
this.indicatorElement.style.backgroundColor = config.color;
}
}
}
// Usage
const statusIndicator = new ConnectionStatusIndicator();
socket.on('connect', () => {
statusIndicator.updateStatus('connected');
});
socket.on('disconnect', () => {
statusIndicator.updateStatus('disconnected');
});
socket.on('connect_error', () => {
statusIndicator.updateStatus('error', 'Connection failed');
});
```
## Monitoring and Logging
### Error Metrics Collection
Collect error metrics for monitoring and debugging.
```javascript
class ErrorMetrics {
constructor() {
this.metrics = {
connectionErrors: 0,
authenticationErrors: 0,
subscriptionErrors: 0,
reconnectionAttempts: 0,
successfulReconnections: 0
};
}
incrementMetric(metricName) {
if (this.metrics.hasOwnProperty(metricName)) {
this.metrics[metricName]++;
}
}
getMetrics() {
return { ...this.metrics };
}
resetMetrics() {
Object.keys(this.metrics).forEach(key => {
this.metrics[key] = 0;
});
}
logMetrics() {
console.log('WebSocket Error Metrics:', this.metrics);
}
}
// Usage
const errorMetrics = new ErrorMetrics();
socket.on('connect_error', () => {
errorMetrics.incrementMetric('connectionErrors');
});
socket.on('news:error', () => {
errorMetrics.incrementMetric('authenticationErrors');
});
socket.on('reconnect_attempt', () => {
errorMetrics.incrementMetric('reconnectionAttempts');
});
socket.on('reconnect', () => {
errorMetrics.incrementMetric('successfulReconnections');
});
// Log metrics periodically
setInterval(() => {
errorMetrics.logMetrics();
}, 300000); // Every 5 minutes
```
## Best Practices
**Error Classification**
* Categorize errors by type (transient vs permanent)
* Implement different retry strategies for different error types
* Log errors with sufficient context for debugging
**Recovery Strategies**
* Use exponential backoff for reconnection attempts
* Implement circuit breaker pattern for cascading failures
* Provide fallback mechanisms when WebSocket fails
**User Experience**
* Display clear error messages and recovery instructions
* Show connection status indicators
* Provide manual retry options for users
**Monitoring**
* Collect error metrics and connection statistics
* Set up alerts for high error rates
* Monitor reconnection success rates
# cURL
Source: https://docs.byul.ai/websocket/examples/curl
Test WebSocket connectivity and troubleshoot connection issues with cURL
**Limited WebSocket Support**: cURL has basic WebSocket support (v7.86+). For full WebSocket functionality, use dedicated clients like Node.js, Python, or PHP.
## Connection Testing
### Basic WebSocket Connection Test
Test if the WebSocket endpoint is accessible:
```bash
# Test WebSocket endpoint connectivity
curl --include \
--no-buffer \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
--header "Sec-WebSocket-Version: 13" \
--header "X-API-Key: byul_api_key" \
https://api.byul.ai/news-v2
```
### Test with Authentication Headers
```bash
# Test with multiple authentication methods
curl --include \
--no-buffer \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: $(echo -n "test" | base64)" \
--header "Sec-WebSocket-Version: 13" \
--header "X-API-Key: byul_api_key" \
--header "Authorization: Bearer byul_api_key" \
wss://api.byul.ai/news-v2
```
## Advanced cURL WebSocket (7.86+)
### WebSocket Connection with Modern cURL
If you have cURL 7.86 or later with WebSocket support:
```bash
# Connect to WebSocket and send messages
curl --include \
--no-buffer \
--header "X-API-Key: byul_api_key" \
--websocket \
wss://api.byul.ai/news-v2 \
--data-raw '{"type":"auth","apiKey":"byul_api_key"}'
```
### Subscribe to News with cURL
```bash
# Send subscription message
curl --websocket \
--header "X-API-Key: byul_api_key" \
wss://api.byul.ai/news-v2 \
--data-raw '{"type":"news:subscribe","minImportance":8,"limit":10,"startDate":"2024-01-01T00:00:00.000Z","endDate":"2024-01-31T23:59:59.999Z"}'
```
## HTTP Alternative Testing
### Test REST API Endpoints
Since WebSocket requires persistent connections, test the related REST endpoints:
```bash
# Test if the base API is working
curl -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key" \
-v
# Check authentication
curl -I -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: byul_api_key"
```
### Health Check Script
```bash
#!/bin/bash
# WebSocket connectivity health check
API_KEY="byul_api_key"
BASE_URL="https://api.byul.ai/api/v2"
WEBSOCKET_URL="wss://api.byul.ai/news-v2"
echo "Testing Byul API Connectivity..."
# Test 1: REST API Health
echo "1. Testing REST API..."
REST_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-X GET "${BASE_URL}/news?limit=1" \
-H "X-API-Key: $API_KEY")
if [ "$REST_STATUS" -eq 200 ]; then
echo " REST API: OK"
else
echo " REST API: Failed (HTTP $REST_STATUS)"
exit 1
fi
# Test 2: WebSocket Endpoint Reachability
echo "2. Testing WebSocket endpoint reachability..."
WS_RESPONSE=$(curl -s -I \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
--header "Sec-WebSocket-Version: 13" \
--header "X-API-Key: $API_KEY" \
https://api.byul.ai/news-v2 2>&1)
if echo "$WS_RESPONSE" | grep -q "101"; then
echo " WebSocket: Endpoint accessible"
elif echo "$WS_RESPONSE" | grep -q "401"; then
echo " WebSocket: Authentication failed"
exit 1
elif echo "$WS_RESPONSE" | grep -q "403"; then
echo " WebSocket: Plan upgrade required (Pro/Enterprise only)"
exit 1
else
echo " WebSocket: Connection test inconclusive"
echo " Response: $WS_RESPONSE"
fi
# Test 3: Network connectivity
echo "3. Testing network connectivity..."
if ping -c 1 api.byul.ai &> /dev/null; then
echo " Network: Host reachable"
else
echo " Network: Host unreachable"
exit 1
fi
echo "All connectivity tests passed!"
```
## Troubleshooting Commands
### Check SSL/TLS Certificate
```bash
# Verify SSL certificate
openssl s_client -connect api.byul.ai:443 -servername api.byul.ai
# Check certificate expiration
echo | openssl s_client -connect api.byul.ai:443 2>/dev/null | openssl x509 -noout -dates
```
### DNS Resolution Testing
```bash
# Test DNS resolution
nslookup api.byul.ai
# Alternative DNS test
dig api.byul.ai
# Test with different DNS servers
dig @8.8.8.8 api.byul.ai
dig @1.1.1.1 api.byul.ai
```
### Network Path Testing
```bash
# Trace network path
traceroute api.byul.ai
# Test specific port connectivity
telnet api.byul.ai 443
# Test with timeout
timeout 5 bash -c "> $LOG_FILE
return 0
else
echo "[$timestamp] Service unhealthy (HTTP $status)" >> $LOG_FILE
send_alert "Byul API service is down (HTTP $status)"
return 1
fi
}
send_alert() {
local message="$1"
# Send email alert (requires mail command)
echo "Alert: $message" | mail -s "Byul API Alert" "$ALERT_EMAIL"
# Or send to Slack (if webhook configured)
# curl -X POST -H 'Content-type: application/json' \
# --data "{\"text\":\"$message\"}" \
# "$SLACK_WEBHOOK_URL"
}
# Run monitoring loop
while true; do
monitor_connection
sleep 60 # Check every minute
done
```
### Performance Testing
```bash
#!/bin/bash
# Test API performance and latency
API_KEY="byul_api_key"
ENDPOINT="https://api.byul.ai/api/v2/news?limit=1"
echo "Testing API Performance..."
echo "Endpoint: $ENDPOINT"
echo "===================="
# Test multiple requests and measure timing
total_time=0
successful_requests=0
failed_requests=0
for i in {1..10}; do
start_time=$(date +%s.%3N)
http_code=$(curl -s -o /dev/null -w "%{http_code}" \
-X GET "$ENDPOINT" \
-H "X-API-Key: $API_KEY")
end_time=$(date +%s.%3N)
duration=$(echo "$end_time - $start_time" | bc -l)
if [ "$http_code" -eq 200 ]; then
echo "Request $i: ${duration}s - OK"
total_time=$(echo "$total_time + $duration" | bc -l)
((successful_requests++))
else
echo "Request $i: Failed (HTTP $http_code)"
((failed_requests++))
fi
done
# Calculate average
if [ $successful_requests -gt 0 ]; then
average_time=$(echo "$total_time / $successful_requests" | bc -l)
printf "==================\n"
printf "Average Response Time: %.3fs\n" $average_time
printf "Success Rate: %d/%d (%.1f%%)\n" \
$successful_requests $((successful_requests + failed_requests)) \
$(echo "$successful_requests * 100 / ($successful_requests + $failed_requests)" | bc -l)
fi
```
## CI/CD Integration
### GitHub Actions WebSocket Test
```yaml
# .github/workflows/websocket-test.yml
name: WebSocket Connectivity Test
on:
schedule:
- cron: '*/15 * * * *' # Every 15 minutes
push:
branches: [ main ]
jobs:
test-websocket:
runs-on: ubuntu-latest
steps:
- name: Test Byul API Connectivity
run: |
# Test REST API
STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: ${{ secrets.BYUL_API_KEY }}")
if [ "$STATUS" -eq 200 ]; then
echo "API connectivity test passed"
else
echo "API connectivity test failed (HTTP $STATUS)"
exit 1
fi
- name: Test WebSocket Endpoint
run: |
# Basic WebSocket endpoint test
curl --fail --max-time 10 \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
--header "Sec-WebSocket-Version: 13" \
--header "X-API-Key: ${{ secrets.BYUL_API_KEY }}" \
https://api.byul.ai/news-v2 || echo "WebSocket test completed"
```
### Docker Health Check
```dockerfile
# Add to your Dockerfile
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f -X GET "https://api.byul.ai/api/v2/news?limit=1" \
-H "X-API-Key: $BYUL_API_KEY" || exit 1
```
## WebSocket-Specific Testing Tools
### Install WebSocket Testing Tools
```bash
# Install websocat (WebSocket client)
curl -L https://github.com/vi/websocat/releases/download/v1.11.0/websocat.x86_64-unknown-linux-musl \
-o websocat && chmod +x websocat
# Test with websocat
echo '{"type":"auth","apiKey":"byul_api_key"}' | \
./websocat wss://api.byul.ai/news-v2
# Install wscat (Node.js WebSocket client)
npm install -g wscat
# Test with wscat
wscat -c "wss://api.byul.ai/news-v2" \
-H "X-API-Key: byul_api_key"
```
**Recommended Approach**: While cURL can test basic connectivity, use dedicated WebSocket clients like `websocat`, `wscat`, or programming language-specific libraries for full WebSocket functionality testing.
## Next Steps
Complete WebSocket implementation examples
Handle WebSocket errors and implement reconnection logic
Secure WebSocket authentication methods
Best practices for stable WebSocket connections
# Node.js
Source: https://docs.byul.ai/websocket/examples/nodejs
Simple Node.js examples for WebSocket news integration
## Basic Connection
```javascript
const { io } = require('socket.io-client');
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
socket.on('connect', () => {
console.log('Connected to Byul AI');
socket.emit('news:subscribe', {
minImportance: 7,
startDate: '2024-01-01T00:00:00.000Z'
});
});
socket.on('news:data', (response) => {
const { data } = response;
const { news } = data;
news.forEach(article => {
console.log(`${article.title} (${article.importanceScore}/10)`);
});
});
```
## With Express Server
```javascript
const express = require('express');
const { io } = require('socket.io-client');
const app = express();
const byulSocket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
// Store latest news
let latestNews = [];
byulSocket.on('connect', () => {
byulSocket.emit('news:subscribe', { minImportance: 6, startDate: '2024-01-01T00:00:00.000Z' });
});
byulSocket.on('news:data', (response) => {
const { data } = response;
const { news } = data;
latestNews = [...news, ...latestNews].slice(0, 50);
});
// API endpoint
app.get('/api/news', (req, res) => {
res.json(latestNews);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
```
## Error Handling
```javascript
const { io } = require('socket.io-client');
const socket = io('wss://api.byul.ai/news-v2', {
reconnection: true,
reconnectionAttempts: 5
});
socket.on('connect', () => {
console.log('Connected');
socket.emit('news:subscribe', { minImportance: 7, startDate: '2024-01-01T00:00:00.000Z' });
});
socket.on('disconnect', () => {
console.log('Disconnected');
});
socket.on('connect_error', (error) => {
console.error('Connection failed:', error.message);
});
socket.on('news:error', (error) => {
console.error('News error:', error.message);
});
socket.on('news:data', (articles) => {
console.log(`Received ${articles.length} articles`);
});
```
## Environment Setup
**package.json**
```json
{
"name": "byul-websocket-client",
"version": "1.0.0",
"dependencies": {
"socket.io-client": "^4.7.0",
"express": "^4.18.0"
}
}
```
**Install and run**
```bash
npm install
BYUL_API_KEY=byul_api_key node app.js
```
## Portfolio Tracking
```javascript
const { io } = require('socket.io-client');
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.BYUL_API_KEY }
});
const portfolio = ['AAPL', 'GOOGL', 'MSFT'];
socket.on('connect', () => {
// Subscribe to portfolio news
portfolio.forEach(symbol => {
socket.emit('news:subscribe', {
symbol,
minImportance: 6,
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-31T23:59:59.999Z'
});
});
});
socket.on('news:data', (articles) => {
articles.forEach(article => {
if (portfolio.includes(article.symbol)) {
console.log(`${article.symbol}: ${article.title}`);
console.log(` Importance: ${article.importance}/10`);
console.log(` URL: ${article.url}\n`);
}
});
});
```
# PHP
Source: https://docs.byul.ai/websocket/examples/php
PHP WebSocket examples for real-time financial news streaming
Build real-time financial applications in PHP using WebSocket connections. Perfect for Laravel applications, trading systems, and fintech platforms that need instant market news delivery.
**WebSocket Requirement**: WebSocket streaming requires **Pro Plan** (\$99/month) or **Enterprise Plan**. [Upgrade here](https://www.byul.ai/api/pricing).
## Basic Connection
```php
'echo-protocol'])
->then(function (WebSocket $conn) use ($apiKey) {
echo "Connected to Byul AI\n";
// Send authentication
$auth_message = json_encode([
'type' => 'auth',
'apiKey' => $apiKey
]);
$conn->send($auth_message);
// Subscribe to high-importance news (date range)
$subscribe_message = json_encode([
'type' => 'news:subscribe',
'minImportance' => 8,
'limit' => 20,
'startDate' => '2024-01-01T00:00:00.000Z',
'endDate' => '2024-01-31T23:59:59.999Z'
]);
$conn->send($subscribe_message);
$conn->on('message', function (MessageInterface $msg) {
$data = json_decode($msg->getPayload(), true);
switch ($data['type'] ?? '') {
case 'auth:success':
echo "Authentication successful\n";
echo "Plan: " . $data['user']['plan'] . "\n";
break;
case 'news:subscribed':
echo "Subscribed to news feed\n";
break;
case 'news:data':
handleNewsData($data);
break;
case 'news:error':
echo "Error: " . $data['message'] . "\n";
break;
}
});
})
->otherwise(function (\Exception $e) {
echo "Could not connect: {$e->getMessage()}\n";
});
function handleNewsData($data) {
$articles = $data['data']['news'] ?? [];
echo "Received " . count($articles) . " breaking news articles\n";
foreach ($articles as $article) {
if ($article['importanceScore'] >= 9) {
echo "CRITICAL: {$article['title']} (Score: {$article['importanceScore']}/10)\n";
// Trigger high-priority alerts
sendCriticalAlert($article);
} else {
echo "📢 {$article['title']} (Score: {$article['importanceScore']}/10)\n";
}
}
}
function sendCriticalAlert($article) {
// Implement your alert logic here
// Send email, SMS, push notification, etc.
echo " → Alert sent for: {$article['title']}\n";
}
```
### Laravel Integration
Create a Laravel service for WebSocket connections:
```php
connector = new Connector();
$this->apiKey = config('services.byul.api_key');
}
public function connect(): \Promise\Promise
{
return $this->connector('wss://api.byul.ai/news-v2')
->then(function (WebSocket $conn) {
$this->connection = $conn;
// Authenticate
$conn->send(json_encode([
'type' => 'auth',
'apiKey' => $this->apiKey
]));
// Handle incoming messages
$conn->on('message', [$this, 'handleMessage']);
Log::info('Connected to Byul WebSocket');
return $conn;
})
->otherwise(function (\Exception $e) {
Log::error('WebSocket connection failed: ' . $e->getMessage());
throw $e;
});
}
public function subscribeToNews(array $filters = [])
{
$message = array_merge([
'type' => 'news:subscribe',
'minImportance' => 7
], $filters);
$this->connection->send(json_encode($message));
}
public function handleMessage($msg)
{
$data = json_decode($msg->getPayload(), true);
switch ($data['type'] ?? '') {
case 'news:data':
$this->processNewsData($data);
break;
case 'auth:success':
Log::info('WebSocket authenticated successfully');
break;
}
}
private function processNewsData($data)
{
$articles = $data['data']['news'] ?? [];
foreach ($articles as $article) {
// Store in database
\App\Models\NewsArticle::updateOrCreate(
['external_id' => $article['_id']],
[
'title' => $article['title'],
'importance_score' => $article['importanceScore'],
'category' => $article['category'],
'symbols' => json_encode($article['symbols'] ?? []),
'published_at' => $article['date'],
'url' => $article['url']
]
);
// Broadcast to users
if ($article['importanceScore'] >= 8) {
broadcast(new \App\Events\BreakingNewsEvent($article));
}
}
}
}
```
## Advanced Examples
### Portfolio Monitoring System
```php
portfolio = $portfolio; // ['AAPL', 'GOOGL', 'MSFT']
$this->webSocketService = new ByulWebSocketService();
}
public function startMonitoring()
{
$this->webSocketService->connect()
->then(function ($conn) {
// Subscribe to portfolio-specific news
foreach ($this->portfolio as $symbol) {
$this->webSocketService->subscribeToNews([
'symbol' => $symbol,
'minImportance' => 6
]);
}
echo "✓ Monitoring " . count($this->portfolio) . " symbols\n";
});
}
public function processNewsForPortfolio($article)
{
$symbols = $article['symbols'] ?? [];
$portfolioMatch = array_intersect($symbols, $this->portfolio);
if (!empty($portfolioMatch)) {
$this->sendPortfolioAlert($article, $portfolioMatch);
}
}
private function sendPortfolioAlert($article, $matchedSymbols)
{
$message = "Portfolio Alert!\n";
$message .= "Symbols: " . implode(', ', $matchedSymbols) . "\n";
$message .= "News: {$article['title']}\n";
$message .= "Importance: {$article['importanceScore']}/10\n";
// Send notification (email, SMS, Slack, etc.)
$this->notificationService->send($message);
}
}
// Usage
$portfolio = ['AAPL', 'GOOGL', 'MSFT', 'AMZN'];
$monitor = new PortfolioNewsMonitor($portfolio);
$monitor->startMonitoring();
```
### Trading Signal Generator
```php
signalRules = [
'fed' => ['importance' => 8, 'action' => 'HEDGE'],
'earnings' => ['importance' => 7, 'action' => 'POSITION'],
'merger' => ['importance' => 8, 'action' => 'BUY']
];
}
public function analyzeNews($article)
{
$category = $article['category'];
$importance = $article['importanceScore'];
$symbols = $article['symbols'] ?? [];
foreach ($this->signalRules as $keyword => $rule) {
if (strpos(strtolower($article['title']), $keyword) !== false) {
if ($importance >= $rule['importance']) {
return $this->generateSignal($article, $rule['action']);
}
}
}
return null;
}
private function generateSignal($article, $action)
{
return [
'action' => $action,
'confidence' => $article['importanceScore'] / 10,
'symbols' => $article['symbols'],
'reason' => $article['title'],
'timestamp' => now(),
'url' => $article['url']
];
}
}
```
### Real-time Dashboard Backend
```php
webSocketService = $webSocketService;
}
public function streamNews(Request $request)
{
$filters = $request->only(['minImportance', 'symbols', 'category']);
return response()->stream(function () use ($filters) {
$this->webSocketService->connect()
->then(function ($conn) use ($filters) {
$this->webSocketService->subscribeToNews($filters);
// Stream data to browser via Server-Sent Events
$conn->on('message', function ($msg) {
$data = json_decode($msg->getPayload(), true);
if ($data['type'] === 'news:data') {
echo "data: " . json_encode($data) . "\n\n";
flush();
}
});
});
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive'
]);
}
public function getMarketSummary()
{
$summary = [
'breaking_news_count' => $this->countBreakingNews(),
'top_categories' => $this->getTopCategories(),
'market_sentiment' => $this->calculateMarketSentiment()
];
return response()->json($summary);
}
}
```
## Error Handling and Reconnection
### Robust Connection Management
```php
connector = new Connector();
$this->apiKey = getenv('BYUL_API_KEY');
}
public function connectWithRetry()
{
$this->connector('wss://api.byul.ai/news-v2')
->then(
[$this, 'onConnect'],
[$this, 'onConnectError']
);
}
public function onConnect(WebSocket $conn)
{
echo "✓ WebSocket connected\n";
$this->currentRetries = 0;
$this->retryDelay = 1;
$conn->on('close', [$this, 'onClose']);
$conn->on('message', [$this, 'onMessage']);
// Send authentication
$conn->send(json_encode([
'type' => 'auth',
'apiKey' => $this->apiKey
]));
}
public function onConnectError($error)
{
echo "✗ Connection failed: " . $error->getMessage() . "\n";
if ($this->currentRetries < $this->maxRetries) {
$this->currentRetries++;
echo "Retrying in {$this->retryDelay}s... (Attempt {$this->currentRetries}/{$this->maxRetries})\n";
sleep($this->retryDelay);
$this->retryDelay *= 2; // Exponential backoff
$this->connectWithRetry();
} else {
echo "Max retries exceeded. Giving up.\n";
}
}
public function onClose($code = null, $reason = null)
{
echo "Connection closed. Code: $code, Reason: $reason\n";
echo "Attempting to reconnect...\n";
sleep(2);
$this->connectWithRetry();
}
public function onMessage($msg)
{
$data = json_decode($msg->getPayload(), true);
// Process different message types
$this->processMessage($data);
}
}
```
## Performance Optimization
### Message Queuing with Redis
```php
redis = new Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
]);
}
public function enqueue($newsData)
{
$message = [
'timestamp' => microtime(true),
'data' => $newsData,
'priority' => $this->calculatePriority($newsData)
];
$this->redis->lpush($this->queueName, json_encode($message));
}
public function processQueue()
{
while (true) {
$message = $this->redis->brpop($this->queueName, 1);
if ($message) {
$data = json_decode($message[1], true);
$this->processNewsMessage($data);
}
}
}
private function calculatePriority($newsData)
{
$importance = $newsData['data']['news'][0]['importanceScore'] ?? 1;
return $importance >= 8 ? 'high' : 'normal';
}
}
```
## Environment Setup
### Installation
```bash
# Install ReactPHP WebSocket client
composer require react/socket
composer require pawl/ratchet-pawl
composer require react/zmq # Optional: for message queuing
# Alternative: ElephantIO for Socket.IO compatibility
composer require elephantio/elephant.io
```
### Configuration
Create a configuration file:
```php
env('BYUL_API_KEY'),
'websocket_url' => 'wss://api.byul.ai/news-v2',
'default_filters' => [
'minImportance' => 6,
'limit' => 50
],
'retry_settings' => [
'max_retries' => 5,
'initial_delay' => 1,
'max_delay' => 30
]
];
```
### Environment Variables
```bash
# .env file
BYUL_API_KEY=byul_api_key
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
```
### Docker Setup
```dockerfile
# Dockerfile for PHP WebSocket application
FROM php:8.1-cli
RUN apt-get update && apt-get install -y \
git \
zip \
unzip \
&& rm -rf /var/lib/apt/lists/*
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
WORKDIR /app
COPY composer.json ./
RUN composer install
COPY . .
CMD ["php", "websocket_client.php"]
```
**Production Tips**:
* Use process managers like Supervisor to keep WebSocket connections alive
* Implement proper logging for debugging connection issues
* Use Redis or message queues for high-throughput scenarios
* Monitor connection health and implement automatic restarts
## Next Steps
Event-driven WebSocket handling with Node.js
Async WebSocket clients with Python
Robust error handling and reconnection strategies
Secure WebSocket authentication methods
# Python
Source: https://docs.byul.ai/websocket/examples/python
Simple Python examples for WebSocket news integration
## Basic Connection
```python
import socketio
import asyncio
sio = socketio.AsyncClient()
@sio.event
async def connect():
print("Connected to Byul AI")
# Subscribe to news
await sio.emit('news:subscribe', {
'minImportance': 7,
'startDate': '2024-01-01T00:00:00.000Z'
})
@sio.on('news:data')
async def handle_news(response):
news = response['data']['news']
for article in news:
print(f"{article['title']} ({article['importanceScore']}/10)")
async def main():
await sio.connect('wss://api.byul.ai/news-v2',
auth={'apiKey': os.getenv('BYUL_API_KEY')})
await sio.wait()
asyncio.run(main())
```
## With Flask API
```python
from flask import Flask, jsonify
import socketio
import threading
app = Flask(__name__)
sio = socketio.AsyncClient()
latest_news = []
@sio.event
async def connect():
await sio.emit('news:subscribe', {'minImportance': 6, 'startDate': '2024-01-01T00:00:00.000Z'})
@sio.on('news:data')
async def handle_news(response):
global latest_news
news = response['data']['news']
latest_news = news + latest_news[:50]
@app.route('/api/news')
def get_news():
return jsonify(latest_news)
def start_websocket():
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
sio.connect('wss://api.byul.ai/news-v2',
auth={'apiKey': os.getenv('BYUL_API_KEY')})
)
# Start WebSocket in background
threading.Thread(target=start_websocket, daemon=True).start()
if __name__ == '__main__':
app.run(port=5000)
```
## Error Handling
```python
import socketio
import asyncio
sio = socketio.AsyncClient()
@sio.event
async def connect():
print("Connected")
await sio.emit('news:subscribe', {'minImportance': 7, 'startDate': '2024-01-01T00:00:00.000Z'})
@sio.event
async def disconnect():
print("Disconnected")
@sio.on('connect_error')
async def connection_error(error):
print(f"Connection failed: {error}")
@sio.on('news:error')
async def news_error(error):
print(f"News error: {error['message']}")
@sio.on('news:data')
async def handle_news(response):
news = response['data']['news']
print(f"Received {len(news)} articles")
async def main():
try:
await sio.connect('wss://api.byul.ai/news-v2')
await sio.wait()
except Exception as e:
print(f"Connection failed: {e}")
asyncio.run(main())
```
## Environment Setup
**requirements.txt**
```txt
python-socketio[asyncio-client]>=5.8.0
flask>=2.3.0
aiohttp>=3.8.0
```
**Install and run**
```bash
pip install -r requirements.txt
BYUL_API_KEY=byul_api_key python app.py
```
## Portfolio Tracking
```python
import socketio
import asyncio
import os
sio = socketio.AsyncClient()
portfolio = ['AAPL', 'GOOGL', 'MSFT']
@sio.event
async def connect():
# Subscribe to portfolio news
for symbol in portfolio:
await sio.emit('news:subscribe', {
'symbol': symbol,
'minImportance': 6,
'startDate': '2024-01-01T00:00:00.000Z',
'endDate': '2024-01-31T23:59:59.999Z'
})
@sio.on('news:data')
async def handle_news(response):
news = response['data']['news']
for article in news:
if article.get('symbols') and any(sym in portfolio for sym in article['symbols']):
symbols_str = ', '.join(article['symbols'])
print(f"{symbols_str}: {article['title']}")
print(f" Importance: {article['importanceScore']}/10")
print(f" URL: {article['url']}\n")
async def main():
await sio.connect('wss://api.byul.ai/news-v2',
auth={'apiKey': os.getenv('BYUL_API_KEY')})
await sio.wait()
asyncio.run(main())
```
## Data Processing
```python
import socketio
import asyncio
import pandas as pd
from datetime import datetime
sio = socketio.AsyncClient()
news_data = []
@sio.event
async def connect():
await sio.emit('news:subscribe', {'minImportance': 7, 'startDate': '2024-01-01T00:00:00.000Z'})
@sio.on('news:data')
async def handle_news(response):
global news_data
news = response['data']['news']
# Add to dataset
for article in news:
news_data.append({
'title': article['title'],
'symbols': article.get('symbols', []),
'importanceScore': article['importanceScore'],
'timestamp': datetime.now()
})
# Keep only last 1000 articles
news_data = news_data[-1000:]
# Create DataFrame for analysis
df = pd.DataFrame(news_data)
# Simple analytics
if len(df) > 10:
avg_importance = df['importanceScore'].mean()
# Flatten symbols list for counting
all_symbols = [sym for symbols in df['symbols'] if symbols for sym in symbols]
if all_symbols:
import pandas as pd
top_symbols = pd.Series(all_symbols).value_counts().head(5)
print(f"Average importance: {avg_importance:.1f}")
print("Top symbols:", top_symbols.to_dict())
async def main():
await sio.connect('wss://api.byul.ai/news-v2',
auth={'apiKey': os.getenv('BYUL_API_KEY')})
await sio.wait()
asyncio.run(main())
```
# React
Source: https://docs.byul.ai/websocket/examples/react
Simple React examples for WebSocket news integration
Build real-time financial applications in React using WebSocket connections. Perfect for trading dashboards, portfolio trackers, and real-time news feeds that require instant market updates.
**WebSocket Requirement**: WebSocket streaming requires **Pro Plan** (\$99/month) or **Enterprise Plan**. [Upgrade here](https://www.byul.ai/api/pricing).
## Basic Connection
```jsx
import { useState, useEffect } from 'react';
import { io } from 'socket.io-client';
function useByulNews() {
const [news, setNews] = useState([]);
const [connected, setConnected] = useState(false);
useEffect(() => {
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.REACT_APP_BYUL_API_KEY }
});
socket.on('connect', () => {
setConnected(true);
socket.emit('news:subscribe', { minImportance: 7, startDate: '2024-01-01T00:00:00.000Z' });
});
socket.on('disconnect', () => {
setConnected(false);
});
socket.on('news:data', (response) => {
const news = response.data.news;
setNews(prev => [...news, ...prev].slice(0, 50));
});
return () => socket.close();
}, []);
return { news, connected };
}
// Usage
function NewsApp() {
const { news, connected } = useByulNews();
return (
News Feed {connected ? 'Connected' : 'Disconnected'}
{news.map(article => (
{article.title}
Importance: {article.importanceScore}/10
Symbols: {article.symbols?.join(', ') || 'General'}
))}
);
}
```
## React Integration
### Context Provider for Global State
```jsx
import React, { createContext, useContext, useState, useEffect } from 'react';
import { io } from 'socket.io-client';
const NewsContext = createContext();
export function NewsProvider({ children }) {
const [news, setNews] = useState([]);
const [connected, setConnected] = useState(false);
const [socket, setSocket] = useState(null);
useEffect(() => {
const newSocket = io('wss://api.byul.ai/news-v2');
newSocket.on('connect', () => {
setConnected(true);
newSocket.emit('news:subscribe', { minImportance: 6, startDate: '2024-01-01T00:00:00.000Z' });
});
newSocket.on('disconnect', () => {
setConnected(false);
});
newSocket.on('news:data', (response) => {
const newsItems = response.data.news;
setNews(prev => [...newsItems, ...prev].slice(0, 100));
});
setSocket(newSocket);
return () => newSocket.close();
}, []);
const subscribeToSymbol = (symbol) => {
if (socket && connected) {
socket.emit('news:subscribe', { symbol, minImportance: 6, startDate: '2024-01-01T00:00:00.000Z' });
}
};
const unsubscribeFromSymbol = (symbol) => {
if (socket && connected) {
socket.emit('news:unsubscribe', { symbol });
}
};
return (
{children}
);
}
export const useNews = () => useContext(NewsContext);
```
## Advanced Examples
### Real-time News Dashboard
```jsx
import React, { useState, useEffect } from 'react';
import { io } from 'socket.io-client';
function NewsDashboard() {
const [articles, setArticles] = useState([]);
const [status, setStatus] = useState('disconnected');
useEffect(() => {
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.REACT_APP_BYUL_API_KEY }
});
socket.on('connect', () => {
setStatus('connected');
socket.emit('news:subscribe', { minImportance: 6, startDate: '2024-01-01T00:00:00.000Z' });
});
socket.on('disconnect', () => {
setStatus('disconnected');
});
socket.on('news:data', (response) => {
const news = response.data.news;
setArticles(prev => [...news, ...prev].slice(0, 100));
});
return () => socket.close();
}, []);
return (
Byul AI News
{status === 'connected' ? 'Connected' : 'Disconnected'}
{articles.map(article => (
{article.title}
{article.symbols && article.symbols.length > 0 && (
{article.symbols.join(', ')}
)}
{article.importanceScore}/10
{new Date(article.date).toLocaleString()}
Read more →
))}
{articles.length === 0 && (
Waiting for news updates...
)}
);
}
export default NewsDashboard;
```
### Portfolio Tracker
```jsx
import React, { useState, useEffect } from 'react';
import { io } from 'socket.io-client';
function PortfolioTracker() {
const [portfolio, setPortfolio] = useState(['AAPL', 'GOOGL', 'MSFT']);
const [news, setNews] = useState([]);
const [newSymbol, setNewSymbol] = useState('');
const [socket, setSocket] = useState(null);
useEffect(() => {
const newSocket = io('wss://api.byul.ai/news-v2');
newSocket.on('connect', () => {
// Subscribe to portfolio news
portfolio.forEach(symbol => {
newSocket.emit('news:subscribe', {
symbol,
minImportance: 6,
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-31T23:59:59.999Z'
});
});
});
newSocket.on('news:data', (response) => {
const news = response.data.news;
const portfolioNews = news.filter(article =>
article.symbols && article.symbols.some(symbol => portfolio.includes(symbol))
);
setNews(prev => [...portfolioNews, ...prev].slice(0, 50));
});
setSocket(newSocket);
return () => newSocket.close();
}, [portfolio]);
const addSymbol = () => {
if (newSymbol && !portfolio.includes(newSymbol.toUpperCase())) {
const symbol = newSymbol.toUpperCase();
setPortfolio(prev => [...prev, symbol]);
if (socket) {
socket.emit('news:subscribe', { symbol, minImportance: 6, startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-31T23:59:59.999Z' });
}
setNewSymbol('');
}
};
const removeSymbol = (symbol) => {
setPortfolio(prev => prev.filter(s => s !== symbol));
if (socket) {
socket.emit('news:unsubscribe', { symbol });
}
};
return (
Portfolio News Tracker
Portfolio ({portfolio.length} symbols)
{portfolio.map(symbol => (
{symbol}
removeSymbol(symbol)}
style={{
marginLeft: '5px',
background: 'none',
border: 'none',
cursor: 'pointer',
color: '#dc3545'
}}
>
×
))}
setNewSymbol(e.target.value)}
style={{ padding: '5px', borderRadius: '3px', border: '1px solid #ddd' }}
/>
Add
Recent News ({news.length})
{news.map(article => (
{article.symbols?.join(', ') || 'General'}
{article.importanceScore}/10
{article.title}
{new Date(article.date).toLocaleString()}
))}
);
}
export default PortfolioTracker;
```
## Error Handling
### Error Handling Hook
```jsx
import { useState, useEffect } from 'react';
import { io } from 'socket.io-client';
function useByulNewsWithErrors() {
const [news, setNews] = useState([]);
const [status, setStatus] = useState('disconnected');
const [error, setError] = useState(null);
useEffect(() => {
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: process.env.REACT_APP_BYUL_API_KEY }
});
socket.on('connect', () => {
setStatus('connected');
setError(null);
socket.emit('news:subscribe', { minImportance: 7, startDate: '2024-01-01T00:00:00.000Z' });
});
socket.on('disconnect', () => {
setStatus('disconnected');
});
socket.on('connect_error', (err) => {
setError(`Connection failed: ${err.message}`);
setStatus('error');
});
socket.on('news:data', (response) => {
const news = response.data.news;
setNews(prev => [...news, ...prev].slice(0, 50));
});
return () => socket.close();
}, []);
return { news, status, error };
}
```
### Connection Status Component
```jsx
function ConnectionStatus({ status, error }) {
const getStatusColor = () => {
switch (status) {
case 'connected': return '#4caf50';
case 'error': return '#f44336';
default: return '#ff9800';
}
};
return (
{status === 'connected' && 'Connected'}
{status === 'disconnected' && 'Disconnected'}
{status === 'error' && `Error: ${error}`}
);
}
```
## Environment Setup
### Installation
```bash
npm install socket.io-client
```
### Environment Variables
Create `.env` file:
```env
REACT_APP_BYUL_API_KEY=byul_api_key
```
### Production Configuration
```jsx
// config/websocket.js
export const websocketConfig = {
url: process.env.REACT_APP_WEBSOCKET_URL || 'wss://api.byul.ai/news-v2',
apiKey: process.env.REACT_APP_BYUL_API_KEY,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
timeout: 20000
};
```
## Next Steps
Event-driven WebSocket handling with Node.js
Async WebSocket clients with Python
Robust error handling and reconnection strategies
# Overview
Source: https://docs.byul.ai/websocket/introduction
WebSocket API for real-time financial news streaming
# WebSocket API
Real-time financial news streaming through WebSocket connections.
**Endpoint:** `wss://api.byul.ai/news-v2`
## Features
* Real-time news delivery
* Event-based messaging
* Subscription filtering
* Automatic reconnection
* Error handling
## Authentication
Authenticate using your API key in the connection options:
```javascript
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' }
});
```
## Events
**Client to Server:**
* `news:subscribe` - Subscribe to news stream
* `news:unsubscribe` - Unsubscribe from stream
* `news:unsubscribe:all` - Unsubscribe from all
**Server to Client:**
* `auth:success` - Authentication confirmed
* `news:data` - Real-time news articles
* `news:subscribed` - Subscription confirmed
* `news:error` - Error notifications
## Plan Requirements
WebSocket streaming requires Pro or Enterprise plan.
| Plan | Support | Connections |
| ----------- | ------- | ----------- |
| Test (Free) | No | - |
| Starter | No | - |
| Pro | Yes | 10 |
| Enterprise | Yes | 50 |
## Quick Example
```javascript
import { io } from 'socket.io-client';
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: 'byul_api_key' }
});
socket.on('connect', () => {
socket.emit('news:subscribe', {
minImportance: 8,
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-31T23:59:59.999Z'
});
});
socket.on('news:data', (response) => {
response.data.news.forEach(article => {
console.log(`${article.title} (${article.importanceScore})`);
});
});
```
## Next Steps
Connect and start streaming
Code examples in multiple languages
API key authentication setup
Connection management guide
# Data Format
Source: https://docs.byul.ai/websocket/news/data-format
News article data structure and format
## Article Structure
News articles are delivered with the following data structure based on the official API:
```json
{
"_id": "67850d7b0123456789abcdef",
"title": "Tesla Stock Surges After Q4 Earnings Beat",
"koTitle": "테슬라 4분기 실적 발표 후 주가 급등",
"content": "Tesla Inc. reported stronger-than-expected Q4 2024 earnings, with revenue beating analyst estimates by 8%. The electric vehicle maker delivered 484,507 vehicles in Q4, up 15% year-over-year, driving shares up 12% in after-hours trading.",
"koContent": "테슬라가 2024년 4분기 실적에서 애널리스트 예상치를 8% 상회하는 매출을 기록했습니다. 이 전기차 제조업체는 4분기에 484,507대를 인도하며 전년 대비 15% 증가했고, 시간외 거래에서 주가가 12% 상승했습니다.",
"url": "https://www.byul.ai/news/tesla-earnings-q4-2024",
"date": "2024-01-15T10:30:00.000Z",
"source": "byul.ai",
"timestamp": 1705401000,
"importanceScore": 8,
"category": "earnings",
"symbols": ["TSLA"],
"sentiment": "positive"
}
```
## Field Descriptions
**Core Fields:**
* `_id` - Unique article identifier
* `title` - Article headline (primary, usually English)
* `koTitle` - Korean title (optional)
* `content` - Article content or summary (optional; may be absent)
* `koContent` - Korean content or summary (optional; may be absent)
* `url` - Link to original article
* `date` - Article date (ISO 8601 format)
**Metadata:**
* `source` - News source name (always "byul.ai")
* `timestamp` - Unix timestamp
* `symbols` - Related stock symbols array (optional)
**Classification:**
* `importanceScore` - Market importance (0-10 integer, higher = more important)
* `category` - News category
* `sentiment` - Sentiment analysis result ("positive", "negative", "neutral") (optional)
## Receiving Data
Listen for incoming news articles:
```javascript
socket.on('news:data', (response) => {
const { data } = response;
const { news } = data;
news.forEach(article => {
console.log(`${article.title}`);
console.log(`Importance: ${article.importanceScore}/10`);
console.log(`Symbols: ${article.symbols?.join(', ') || 'General'}`);
console.log(`Sentiment: ${article.sentiment || 'N/A'}`);
console.log(`Source: ${article.source}`);
});
});
```
## WebSocket Response Format
The complete WebSocket response structure:
```json
{
"type": "news",
"data": {
"news": [
{
"_id": "67850d7b0123456789abcde1",
"title": "Breaking: Fed Issues Emergency Statement",
"koTitle": "속보: 연준 긴급성명 발표",
"url": "https://www.byul.ai/news/fed-emergency-statement",
"date": "2024-01-15T14:30:00.000Z",
"source": "byul.ai",
"timestamp": 1705415400,
"importanceScore": 10,
"category": "fed",
"symbols": [],
"sentiment": "neutral"
}
],
"hasMore": false,
"nextCursor": null,
"total": 1
},
"timestamp": "2024-01-15T14:30:15Z",
"isRealTimeUpdate": true
}
```
## Data Validation
Always validate incoming data structure:
```javascript
function validateArticle(article) {
return (
article._id &&
article.title &&
typeof article.importanceScore === 'number' &&
Number.isInteger(article.importanceScore) &&
article.importanceScore >= 0 && article.importanceScore <= 10 &&
article.date &&
(!article.sentiment || ['positive', 'negative', 'neutral'].includes(article.sentiment))
);
}
socket.on('news:data', (response) => {
const { data } = response;
const { news } = data;
const validArticles = news.filter(validateArticle);
console.log(`Processing ${validArticles.length} valid articles`);
validArticles.forEach(article => {
processArticle(article);
});
});
```
## Language Support
Articles include multi-language titles:
* `title` - Primary title (usually English)
* `koTitle` - Korean version (optional)
Use the appropriate title field based on your application's language requirements.
# Error Codes
Source: https://docs.byul.ai/websocket/news/error-codes
News WebSocket error codes and handling
## Error Response Format
All news errors follow a consistent structure with detailed information for debugging:
```json
{
"code": "SUBSCRIPTION_FAILED",
"message": "Minimum importance must be between 0-10",
"details": {
"field": "minImportance",
"value": 15,
"allowedRange": "0-10"
},
"timestamp": "2024-01-15T10:30:00Z"
}
```
## News Subscription Error Codes
These errors are specific to news subscription operations and should be handled appropriately in your application.
### Official WebSocket Error Codes
Based on the official API documentation, these are the only WebSocket error codes:
| Error Code | Description | Action |
| :------------------------ | :---------------------------------------------- | :--------------- |
| `AUTHENTICATION_FAILED` | API key authentication failed | Check API key |
| `NOT_AUTHENTICATED` | Client not authenticated, reconnection required | Reconnect |
| `SUBSCRIPTION_FAILED` | Subscription setup failed | Check parameters |
| `WEBSOCKET_NOT_SUPPORTED` | WebSocket not available on current plan | Upgrade plan |
## Error Handling Strategy
```javascript
socket.on('news:error', (error) => {
console.error(`[${error.code}] ${error.message}`);
switch (error.code) {
case 'AUTHENTICATION_FAILED':
handleAuthFailed(error);
break;
case 'NOT_AUTHENTICATED':
handleNotAuthenticated(error);
break;
case 'SUBSCRIPTION_FAILED':
handleSubscriptionFailed(error);
break;
case 'WEBSOCKET_NOT_SUPPORTED':
handleWebSocketNotSupported(error);
break;
default:
handleUnknownError(error);
}
});
```
## Implementation Examples
### Authentication Error Handling
```javascript
function handleAuthFailed(error) {
console.error('Authentication failed:', error.message);
// Check API key format
if (!byul_api_key?.startsWith('byul_v2_')) {
console.error('Invalid API key format. Must start with byul_v2_');
}
// Disconnect and require re-authentication
socket.disconnect();
}
```
### Reconnection for Lost Authentication
```javascript
function handleNotAuthenticated(error) {
console.warn('Authentication lost:', error.message);
// Attempt reconnection with authentication
socket.disconnect();
setTimeout(() => {
socket.connect();
}, 2000);
}
```
## Error Details by Code
### AUTHENTICATION\_FAILED
**Cause**: API key authentication failed
**Common Issues**:
* Invalid API key format (must start with `byul_v2_`)
* API key doesn't exist
* API key has been revoked
**Solution**: Verify API key from dashboard
### NOT\_AUTHENTICATED
**Cause**: Client not authenticated, reconnection required
**Common Issues**:
* Connection dropped during authentication
* Session expired
* Authentication state lost
**Solution**: Reconnect with valid API key
### SUBSCRIPTION\_FAILED
**Cause**: News subscription setup failed
**Common Issues**:
* Invalid `minImportance` value (must be 0-10)
* Invalid `limit` value (must be 1-100)
* Invalid subscription parameters
**Solution**: Validate parameters before subscribing
### WEBSOCKET\_NOT\_SUPPORTED
**Cause**: WebSocket not available on current plan
**Affected Plans**: Test (Free), Starter ($19/month) **Solution**: Upgrade to Pro ($99/month) or Enterprise plan
## Client-Side Validation
```javascript
class SubscriptionValidator {
static validate(params) {
const errors = [];
if (params.minImportance && (params.minImportance < 0 || params.minImportance > 10)) {
errors.push('minImportance must be between 0 and 10');
}
if (params.limit && (params.limit < 1 || params.limit > 100)) {
errors.push('limit must be between 1 and 100');
}
return errors;
}
}
// Usage
const params = { minImportance: 7, limit: 20 };
const validationErrors = SubscriptionValidator.validate(params);
if (validationErrors.length === 0) {
socket.emit('news:subscribe', params);
} else {
console.error('Validation failed:', validationErrors);
}
```
## Best Practices
**Error Logging**
* Log all errors with full context for debugging
* Include timestamp and user session information
* Monitor error rates and patterns
**User Experience**
* Provide clear, actionable error messages
* Show suggestions when available (e.g., symbol suggestions)
* Implement graceful degradation for non-critical errors
**Error Recovery**
* Implement automatic retry for transient errors
* Respect rate limits and retry-after headers
* Clean up failed subscriptions to prevent limit issues
# Filtering
Source: https://docs.byul.ai/websocket/news/filtering
## Importance Filtering
Filter news by importance level to control data volume:
```javascript
// High-importance news only (9-10)
socket.emit('news:subscribe', {
minImportance: 9
});
// Medium-importance and above (6-10)
socket.emit('news:subscribe', {
minImportance: 6
});
```
**Importance Levels:**
* `10` - Market-moving breaking news
* `8-9` - High-impact company/sector news
* `6-7` - Notable market developments
* `4-5` - Regular business news
* `1-3` - Minor updates and announcements
## Symbol Filtering
Subscribe to news for specific stocks:
```javascript
// Single symbol
socket.emit('news:subscribe', {
symbol: 'AAPL',
minImportance: 6
});
// Multiple symbols (separate subscriptions)
const portfolio = ['AAPL', 'GOOGL', 'MSFT'];
portfolio.forEach(symbol => {
socket.emit('news:subscribe', {
symbol,
minImportance: 5
});
});
```
```javascript
// Earnings reports only
socket.emit('news:subscribe', {
minImportance: 6
});
// Market and economy news
socket.emit('news:subscribe', {
minImportance: 7
});
socket.emit('news:subscribe', {
minImportance: 8
});
```
## Combined Filtering
Use multiple filters together:
```javascript
// High-importance AAPL news
socket.emit('news:subscribe', {
symbol: 'AAPL',
minImportance: 8,
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-31T23:59:59.999Z'
});
// General high-importance market news
socket.emit('news:subscribe', {
minImportance: 7,
startDate: '2024-01-01T00:00:00.000Z'
});
```
Category filtering is not supported in subscriptions. The `category` field is read-only and only appears in response data for classification purposes.
## Client-Side Filtering
Additional filtering on received data:
```javascript
socket.on('news:data', (response) => {
const { data } = response;
const { news } = data;
// Filter by category
const fedNews = news.filter(article =>
article.category === 'fed'
);
// Filter by sentiment
const positiveNews = news.filter(article =>
article.sentiment === 'positive'
);
// Filter by time (last 1 hour)
const recent = news.filter(article => {
const publishTime = new Date(article.date);
const hourAgo = new Date(Date.now() - 60 * 60 * 1000);
return publishTime > hourAgo;
});
// Filter by keywords in title
const filtered = news.filter(article =>
article.title.toLowerCase().includes('earnings') ||
article.title.toLowerCase().includes('acquisition')
);
// Filter by symbols
const appleNews = news.filter(article =>
article.symbols && article.symbols.includes('AAPL')
);
});
```
## Subscription Management
Manage multiple filtered subscriptions:
```javascript
class NewsSubscriptionManager {
constructor(socket) {
this.socket = socket;
this.subscriptions = new Map();
}
subscribe(id, filters) {
this.socket.emit('news:subscribe', filters);
this.subscriptions.set(id, filters);
}
unsubscribe(id) {
const filters = this.subscriptions.get(id);
if (filters) {
this.socket.emit('news:unsubscribe', filters);
this.subscriptions.delete(id);
}
}
updateSubscription(id, newFilters) {
this.unsubscribe(id);
this.subscribe(id, newFilters);
}
}
// Usage
const manager = new NewsSubscriptionManager(socket);
manager.subscribe('portfolio', {
symbol: 'AAPL',
minImportance: 6
});
manager.subscribe('market', {
minImportance: 8
});
```
# Responses
Source: https://docs.byul.ai/websocket/news/responses
WebSocket response formats and event structures
## News Data Response
Receive real-time news articles through the `news:data` event.
```javascript
socket.on('news:data', (response) => {
console.log('New articles:', response);
});
```
**Response Structure:**
```json
{
"type": "news",
"data": {
"news": [
{
"_id": "67850d7b0123456789abcde1",
"title": "Breaking: Fed Issues Emergency Statement",
"koTitle": "속보: 연준 긴급성명 발표",
"content": "The Federal Reserve issued an unexpected emergency statement addressing current market volatility and reaffirming its commitment to price stability. The statement comes amid heightened concerns over inflation and economic uncertainty.",
"koContent": "연방준비제도이사회가 현재의 시장 변동성을 다루고 물가 안정에 대한 약속을 재확인하는 예상치 못한 긴급 성명을 발표했습니다. 이 성명은 인플레이션과 경제 불확실성에 대한 우려가 높아지는 가운데 나왔습니다.",
"url": "https://www.byul.ai/news/fed-emergency-statement",
"date": "2024-01-15T14:30:00.000Z",
"source": "byul.ai",
"timestamp": 1705415400,
"importanceScore": 10,
"category": "fed",
"symbols": [],
"sentiment": "neutral"
}
],
"hasMore": false,
"nextCursor": null,
"total": 1
},
"timestamp": "2024-01-15T14:30:15Z",
"isRealTimeUpdate": true
}
```
**Response Fields:**
* `type` - Event type ("news")
* `data` - News data object containing `news` array, `hasMore`, `nextCursor`, `total`
* `timestamp` - Server transmission time
* `isRealTimeUpdate` - Whether this is a real-time update
## Connection Status Response
Monitor connection health and usage statistics.
```javascript
socket.on('connection:status', (status) => {
console.log('Connection status:', status);
});
```
**Response Structure:**
```json
{
"status": "connected",
"connectionsUsed": 1,
"maxConnections": 10,
"plan": "pro",
"rateLimit": {
"remaining": 119,
"resetTime": "2024-01-15T15:00:00Z"
}
}
```
**Status Fields:**
* `status` - Connection state (`connected`, `disconnected`, `limited`)
* `connectionsUsed` - Current active connections
* `maxConnections` - Plan connection limit
* `plan` - Subscription plan type
* `rateLimit` - Rate limiting information
## Subscription Confirmation
Receive confirmation when subscriptions are activated.
```javascript
socket.on('news:subscribed', (confirmation) => {
console.log('Subscription confirmed:', confirmation);
});
```
**Response Structure:**
```json
{
"type": "news",
"params": {
"limit": 20,
"minImportance": 5,
"symbol": "AAPL"
},
"message": "Successfully subscribed to news feed - 실시간 업데이트 활성화됨"
}
```
**Confirmation Fields:**
* `type` - Subscription type
* `params` - Applied filter settings
* `message` - Confirmation message
## Batch News Response
Large news updates may be delivered as batches.
```javascript
socket.on('news:data', (batch) => {
console.log(`Batch update: ${batch.articles.length} articles`);
});
```
**Batch Structure:**
```json
{
"type": "news_batch",
"articles": [
// Array of article objects
],
"batchId": "batch_20240115_143015",
"totalArticles": 5,
"timestamp": "2024-01-15T14:30:15Z",
"reason": "high_volume"
}
```
**Batch Fields:**
* `batchId` - Unique batch identifier
* `totalArticles` - Total articles in batch
* `reason` - Batching reason (`high_volume`, `scheduled`)
## Ping Response
Server may send ping messages to check connection health.
```javascript
socket.on('ping', (data) => {
console.log('Ping received:', data.timestamp);
// Respond with pong
socket.emit('pong', {
timestamp: Date.now()
});
});
```
**Ping Structure:**
```json
{
"timestamp": "2024-01-15T14:30:00Z",
"serverId": "ws-server-01"
}
```
## Response Handling Best Practices
### Type Checking
Always validate response structure:
```javascript
socket.on('news:data', (response) => {
if (response.type && response.data && response.data.news && Array.isArray(response.data.news)) {
response.data.news.forEach(article => {
if (article._id && article.title) {
processArticle(article);
}
});
}
});
```
### Error Handling
Handle malformed responses gracefully:
```javascript
socket.on('news:data', (response) => {
try {
const { data, timestamp } = response;
const { news } = data;
if (!news || !Array.isArray(news)) {
console.warn('Invalid news array received');
return;
}
console.log(`Processing ${news.length} articles`);
news.forEach(processArticle);
} catch (error) {
console.error('Error processing news response:', error);
}
});
```
### Response Logging
Log responses for debugging:
```javascript
const logResponse = (eventName, data) => {
console.log(`[${new Date().toISOString()}] ${eventName}:`, {
type: data.type || 'unknown',
count: data.data?.news?.length || data.data?.total || 0,
timestamp: data.timestamp
});
};
socket.on('news:data', (data) => logResponse('news:data', data));
socket.on('connection:status', (data) => logResponse('connection:status', data));
```
# Subscription
Source: https://docs.byul.ai/websocket/news/subscription
Subscribe and unsubscribe from news events
## Subscribe to News
Start receiving real-time news updates by subscribing to specific criteria.
```javascript
socket.emit('news:subscribe', {
minImportance: 7,
symbol: 'AAPL',
limit: 20,
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-01-31T23:59:59.999Z'
});
```
**Parameters:**
| Parameter | Type | Description | Default |
| --------------- | ------- | ------------------------------------- | ------- |
| `minImportance` | integer | Minimum importance level (0-10) | 0 |
| `symbol` | string | Stock symbol filter | - |
| `limit` | integer | Max articles per batch (1-100) | 10 |
| `startDate` | string | Start of date range filter (ISO 8601) | - |
| `endDate` | string | End of date range filter (ISO 8601) | - |
## Subscription Confirmation
Receive confirmation when subscription is successful.
```javascript
socket.on('news:subscribed', (confirmation) => {
console.log('Subscription confirmed:', confirmation);
});
```
**Response (official format):**
```json
{
"type": "news",
"params": {
"limit": 20,
"minImportance": 7,
"symbol": "AAPL"
},
"message": "Successfully subscribed to news feed - 실시간 업데이트 활성화됨"
}
```
## Unsubscribe
Remove specific subscriptions or unsubscribe from all topics.
```javascript
// Unsubscribe from specific symbol
socket.emit('news:unsubscribe', {
symbol: 'AAPL'
});
// Unsubscribe from all news
socket.emit('news:unsubscribe:all');
```
## Multiple Subscriptions
Subscribe to multiple criteria simultaneously.
```javascript
// Subscribe to high-importance general news
socket.emit('news:subscribe', {
minImportance: 9
});
// Subscribe to AAPL news
socket.emit('news:subscribe', {
symbol: 'AAPL',
minImportance: 6
});
```
# Quickstart
Source: https://docs.byul.ai/websocket/quickstart
Get up and running with Byul WebSocket API in 5 minutes
## WebSocket Connection Setup
Connect to real-time financial news streams using WebSocket API.
**Setup Steps:**
* Configure WebSocket client with API key authentication
* Subscribe to filtered news streams
* Handle real-time data events
* Implement error handling and reconnection logic
### Prerequisites
WebSocket requires **Pro Plan** (\$99/month) or **Enterprise Plan**.
[Upgrade your plan](https://www.byul.ai/api/pricing) if needed.
### Step 1: Get Your API Key
1. Login to [Byul API Dashboard](https://www.byul.ai/api/dashboard)
2. Your API key is automatically generated and displayed
3. Copy your API key (starts with `byul_v2_`)
### Step 2: Install Dependencies
```bash
npm install socket.io-client
```
```bash
pip install python-socketio[asyncio-client]
```
```bash
npm install socket.io-client
```
### Step 3: Create Your First Connection
```javascript
const { io } = require('socket.io-client');
// Replace with your actual API key
const API_KEY = 'byul_api_key';
// Connect to WebSocket
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: API_KEY }
});
// Handle connection
socket.on('connect', () => {
console.log('Connected to Byul WebSocket');
// Subscribe to high-importance news
socket.emit('news:subscribe', {
minImportance: 7,
startDate: '2024-01-01T00:00:00.000Z'
});
});
// Handle incoming news
socket.on('news:data', (response) => {
const { news } = response.data;
news.forEach(article => {
console.log(article.title);
console.log(`Importance: ${article.importanceScore}/10`);
console.log(`Category: ${article.category}`);
console.log('---');
});
});
// Handle authentication success
socket.on('auth:success', (data) => {
console.log('Authenticated successfully:', data.user.plan);
});
// Handle errors
socket.on('news:error', (error) => {
console.error('Error:', error.message);
});
console.log('Connecting to Byul WebSocket...');
```
```python
import asyncio
import socketio
# Replace with your actual API key
API_KEY = 'byul_api_key'
sio = socketio.AsyncClient()
@sio.event
async def connect():
print('Connected to Byul WebSocket')
# Subscribe to high-importance news
await sio.emit('news:subscribe', {
'minImportance': 7,
'startDate': '2024-01-01T00:00:00.000Z'
})
@sio.on('news:data')
async def handle_news(response):
news = response['data']['news']
for article in news:
print(article['title'])
print(f"Importance: {article['importanceScore']}/10")
print(f"Category: {article['category']}")
print('---')
@sio.on('auth:success')
async def auth_success(data):
print(f"Authenticated successfully: {data['user']['plan']}")
@sio.on('news:error')
async def news_error(error):
print(f"Error: {error['message']}")
async def main():
print('Connecting to Byul WebSocket...')
await sio.connect('wss://api.byul.ai/news-v2',
auth={'apiKey': API_KEY})
await sio.wait()
if __name__ == '__main__':
asyncio.run(main())
```
```jsx
import React, { useState, useEffect } from 'react';
import { io } from 'socket.io-client';
// Replace with your actual API key
const API_KEY = 'byul_api_key';
function QuickstartNews() {
const [news, setNews] = useState([]);
const [status, setStatus] = useState('Connecting...');
useEffect(() => {
console.log('Connecting to Byul WebSocket...');
const socket = io('wss://api.byul.ai/news-v2', {
auth: { apiKey: API_KEY }
});
socket.on('connect', () => {
console.log('Connected to Byul WebSocket');
setStatus('Connected');
// Subscribe to high-importance news
socket.emit('news:subscribe', {
minImportance: 7,
startDate: '2024-01-01T00:00:00.000Z'
});
});
socket.on('news:data', (response) => {
const { news: newNews } = response.data;
setNews(prev => [...newNews, ...prev].slice(0, 20)); // Keep latest 20
});
socket.on('auth:success', (data) => {
console.log('Authenticated successfully:', data.user.plan);
setStatus(`Connected (${data.user.plan})`);
});
socket.on('news:error', (error) => {
console.error('Error:', error.message);
setStatus(`Error: ${error.message}`);
});
return () => socket.close();
}, []);
return (
Byul WebSocket Quickstart
Status: {status}
Latest News ({news.length})
{news.map(article => (
{article.title}
Importance: {article.importanceScore}/10 | Category: {article.category}
{new Date(article.date).toLocaleString()}
))}
{news.length === 0 && status.includes('Connected') && (
Waiting for news updates...
)}
);
}
export default QuickstartNews;
```
### Step 4: Run Your Code
```bash
node your-websocket-app.js
```
Expected output:
```
Connecting to Byul WebSocket...
Connected to Byul WebSocket!
Authenticated successfully: pro
Breaking: Fed Issues Emergency Statement
Importance: 10/10
Category: fed
---
```
```bash
python your-websocket-app.py
```
Expected output:
```
Connecting to Byul WebSocket...
Connected to Byul WebSocket!
Authenticated successfully: pro
Breaking: Fed Issues Emergency Statement
Importance: 10/10
Category: fed
---
```
```bash
npm start
```
Your browser will show a live-updating news feed with connection status.
## Connection Complete
WebSocket connection established and receiving real-time news updates.
### What's Next?
Learn about API key authentication and security best practices
Filter news by importance, symbols, and categories
Handle connection errors and implement retry logic
See production-ready implementation examples
## Troubleshooting
### Common Issues
**Authentication Failed**
* Verify API key format (starts with `byul_v2_`)
* Check API key at Dashboard
* Confirm Pro or Enterprise plan access
**WebSocket Not Supported**
* Requires Pro or Enterprise plan
* Check current plan status
**Connection Timeout**
* Verify network connectivity
* Check firewall settings
* Test from different network if needed
### Additional Resources
* Full [WebSocket Documentation](/websocket/introduction)
* [Community Forum](https://www.byul.ai/community)
* [Technical Support](https://www.byul.ai/contact)
**Security**: Use environment variables in production to store API keys securely:
```bash
export BYUL_API_KEY=byul_api_key
```