API Documentation
NeuraScale provides comprehensive APIs for integrating with brain-computer interface devices, managing neural data, and building applications. Our API ecosystem includes REST, GraphQL, WebSocket, and gRPC interfaces to support various integration patterns.
API Overview
Quick Start
Authentication
All API requests require authentication using JWT tokens:
# Get access token
curl -X POST https://api.neurascale.io/v2/auth/login \
-H "Content-Type: application/json" \
-d '{"email": "your-email@example.com", "password": "your-password"}'
# Use token in requests
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
https://api.neurascale.io/v2/devices
Base URLs
Environment | Base URL | Status |
---|---|---|
Production | https://api.neurascale.io | 🚀 Coming Soon |
Staging | https://staging-api.neurascale.io | 🚀 Coming Soon |
Development | http://localhost:8000 | ✓ Available |
Rate Limits
API Type | Rate Limit | Notes |
---|---|---|
REST API | 1,000 requests/hour | Per user token |
GraphQL | 500 queries/hour | Complexity-weighted |
WebSocket | 10 connections | Per user |
gRPC | Unlimited | Production use only |
REST API v2 ✓ Available
Our REST API follows OpenAPI 3.0 specification and provides standard HTTP operations for all platform resources.
The REST API is currently available for local development. Production deployment coming soon with full authentication and rate limiting.
Devices
Device Management Endpoints
# List all devices
GET /v2/devices
# Get device details
GET /v2/devices/{device_id}
# Start device streaming
POST /v2/devices/{device_id}/stream/start
# Stop device streaming
POST /v2/devices/{device_id}/stream/stop
# Update device configuration
PATCH /v2/devices/{device_id}/config
Example: Connect OpenBCI Device
const response = await fetch('https://api.neurascale.io/v2/devices/openbci_001/stream/start', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json'
},
body: JSON.stringify({
sample_rate: 250,
channels: [1, 2, 3, 4, 5, 6, 7, 8],
filters: {
notch: 60,
highpass: 0.5,
lowpass: 100
}
})
});
const result = await response.json();
console.log('Stream started:', result.stream_id);
GraphQL API 🚀 Coming Soon
Our GraphQL API provides a unified interface for querying related data efficiently with strong typing and real-time subscriptions.
GraphQL API is under active development and will be available in the next release. The schema and examples below show the planned implementation.
GraphQL Endpoint
POST https://api.neurascale.io/graphql
Schema Overview
Queries
Common Queries
# Get devices with recent sessions
query GetDevicesWithSessions {
devices {
id
name
status
sessions(last: 5) {
id
name
startTime
status
recordings {
id
duration
sampleCount
quality
}
}
}
}
# Query specific session data
query GetSessionData($sessionId: ID!) {
session(id: $sessionId) {
id
name
startTime
endTime
device {
id
name
type
}
recordings {
id
channelCount
sampleRate
duration
artifacts {
type
startTime
endTime
}
}
analysis {
id
modelType
accuracy
predictions {
timestamp
label
confidence
}
}
}
}
# Search sessions with filters
query SearchSessions($filters: SessionFilters) {
sessions(filters: $filters) {
edges {
node {
id
name
startTime
tags
metadata
}
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
}
WebSocket API 🔧 Beta
For real-time bidirectional communication, our WebSocket API provides low-latency streaming of neural data and events.
WebSocket API is currently in beta with core functionality available. Full production features including compression and advanced event filtering coming soon.
Connection
const ws = new WebSocket('wss://api.neurascale.io/ws');
// Authentication
ws.onopen = () => {
ws.send(JSON.stringify({
type: 'auth',
token: 'YOUR_ACCESS_TOKEN'
}));
};
// Handle messages
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
};
Message Types
Data Streaming
Neural Data Streaming
// Subscribe to data stream
ws.send(JSON.stringify({
type: 'subscribe',
topic: 'neural_data',
session_id: 'session_123'
}));
// Real-time data message format
{
"type": "neural_data",
"timestamp": 1705317045123,
"device_id": "openbci_001",
"session_id": "session_123",
"channels": [
{ "number": 1, "value": 1.23, "quality": 0.98 },
{ "number": 2, "value": 4.56, "quality": 0.99 },
{ "number": 3, "value": 7.89, "quality": 0.97 }
],
"events": [
{
"type": "stimulus",
"timestamp": 1705317045120,
"data": { "stimulus_id": "stim_001" }
}
]
}
// Batch data for efficiency
{
"type": "neural_data_batch",
"batch_id": "batch_123",
"timestamp_start": 1705317045000,
"timestamp_end": 1705317049000,
"sample_count": 1000,
"compressed_data": "base64_encoded_data"
}
gRPC API 📅 Planned
For high-performance applications requiring low latency and efficient binary protocol, our gRPC API provides streaming interfaces.
gRPC API is planned for future release to support high-frequency neural data streaming. The protocol buffers and examples below show the planned implementation.
Protocol Buffers
// neural_service.proto
syntax = "proto3";
package neurascale.v1;
service NeuralService {
// Streaming neural data
rpc StreamNeuralData(StreamRequest) returns (stream NeuralDataPacket);
// Bidirectional device control
rpc DeviceControl(stream DeviceCommand) returns (stream DeviceResponse);
// Analysis service
rpc AnalyzeData(AnalysisRequest) returns (AnalysisResponse);
}
message NeuralDataPacket {
string device_id = 1;
int64 timestamp = 2;
repeated ChannelData channels = 3;
repeated Event events = 4;
}
message ChannelData {
int32 channel_number = 1;
float value = 2;
float quality = 3;
}
message Event {
string type = 1;
int64 timestamp = 2;
map<string, string> metadata = 3;
}
Client Examples
Python
Python gRPC Client
import grpc
from neurascale.v1 import neural_service_pb2_grpc, neural_service_pb2
# Create channel with authentication
credentials = grpc.ssl_channel_credentials()
call_credentials = grpc.access_token_call_credentials('YOUR_TOKEN')
composite_credentials = grpc.composite_channel_credentials(
credentials, call_credentials
)
channel = grpc.secure_channel(
'api.neurascale.io:443',
composite_credentials
)
# Create service stub
stub = neural_service_pb2_grpc.NeuralServiceStub(channel)
# Stream neural data
request = neural_service_pb2.StreamRequest(
session_id='session_123',
device_ids=['openbci_001']
)
try:
for packet in stub.StreamNeuralData(request):
print(f"Received data from {packet.device_id}")
for channel in packet.channels:
print(f" Channel {channel.channel_number}: {channel.value}")
except grpc.RpcError as e:
print(f"Error: {e.code()} - {e.details()}")
Error Handling
HTTP Status Codes
Code | Description | Common Causes |
---|---|---|
200 | Success | Request completed successfully |
201 | Created | Resource created successfully |
400 | Bad Request | Invalid request format or parameters |
401 | Unauthorized | Missing or invalid authentication |
403 | Forbidden | Insufficient permissions |
404 | Not Found | Resource does not exist |
409 | Conflict | Resource conflict (e.g., device already in use) |
422 | Unprocessable Entity | Valid request but business logic error |
429 | Too Many Requests | Rate limit exceeded |
500 | Internal Server Error | Server-side error |
503 | Service Unavailable | Service temporarily unavailable |
Error Response Format
{
"error": {
"code": "DEVICE_NOT_FOUND",
"message": "Device with ID 'openbci_001' not found",
"details": {
"resource_type": "device",
"resource_id": "openbci_001",
"available_devices": ["openbci_002", "emotiv_001"]
},
"request_id": "req_123456789",
"timestamp": "2024-01-15T10:30:45.123Z"
}
}
Common Error Codes
Code | Description | Resolution |
---|---|---|
INVALID_TOKEN | JWT token is invalid or expired | Refresh token or re-authenticate |
DEVICE_NOT_FOUND | Specified device doesn’t exist | Check device ID and availability |
DEVICE_BUSY | Device is already in use | Wait or use different device |
SESSION_NOT_FOUND | Session doesn’t exist | Verify session ID |
INSUFFICIENT_PERMISSIONS | User lacks required permissions | Contact administrator |
RATE_LIMIT_EXCEEDED | Too many requests | Implement backoff and retry |
STREAM_UNAVAILABLE | Data stream is not active | Start streaming first |
INVALID_CONFIGURATION | Device configuration is invalid | Check configuration parameters |
For detailed API documentation including all endpoints, parameters, and examples, visit our interactive API documentation at docs.neurascale.io/api .