Skip to main content

API Documentation

PianoRhythm Server provides both REST and WebSocket APIs for comprehensive client integration. This document covers the API architecture, authentication, and general usage patterns.

๐Ÿ”Œ API Overviewโ€‹

API Typesโ€‹

  • REST API - HTTP endpoints for standard operations
  • WebSocket API - Real-time bidirectional communication
  • GraphQL - (Future) Flexible query interface

Base URLsโ€‹

  • Production: https://api.pianorhythm.io
  • Staging: https://staging-api.pianorhythm.io
  • Development: http://localhost:8080

๐Ÿ” Authenticationโ€‹

JWT Token Authenticationโ€‹

All authenticated endpoints require a valid JWT token in the Authorization header:

Authorization: Bearer <jwt_token>

Token Structureโ€‹

{
"sub": "user_id",
"username": "user123",
"roles": ["member", "pro"],
"exp": 1640995200,
"iat": 1640908800
}

Authentication Flowโ€‹

  1. Login - POST /api/auth/login with credentials
  2. Token Receipt - Server returns JWT token
  3. Token Usage - Include token in subsequent requests
  4. Token Refresh - Use refresh token before expiration

Role-Based Access Controlโ€‹

  • Guest - Limited read-only access
  • Member - Standard user features
  • Pro - Premium features and rooms
  • Moderator - Moderation capabilities
  • Admin - Full system access

๐Ÿ“ก REST APIโ€‹

General Patternsโ€‹

Request Formatโ€‹

POST /api/endpoint
Content-Type: application/json
Authorization: Bearer <token>

{
"parameter": "value"
}

Response Formatโ€‹

{
"success": true,
"data": {
"result": "data"
},
"message": "Operation completed successfully"
}

Error Response Formatโ€‹

{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input parameters",
"details": {
"field": "username",
"issue": "Username already exists"
}
}
}

Core Endpointsโ€‹

Authenticationโ€‹

  • POST /api/auth/login - User login
  • POST /api/auth/register - User registration
  • POST /api/auth/refresh - Token refresh
  • POST /api/auth/logout - User logout
  • GET /api/auth/validate-token - Token validation

Usersโ€‹

  • GET /api/users/profile - Get user profile
  • PUT /api/users/profile - Update user profile
  • GET /api/users/{user_id} - Get public user info
  • POST /api/users/avatar - Upload avatar image
  • GET /api/users/friends - Get friends list

Roomsโ€‹

  • GET /api/rooms - List public rooms
  • POST /api/rooms - Create new room
  • GET /api/rooms/{room_id} - Get room details
  • PUT /api/rooms/{room_id} - Update room settings
  • DELETE /api/rooms/{room_id} - Delete room

Billing (Pro Members)โ€‹

  • GET /api/billing/products - Available products
  • POST /api/billing/checkout - Create checkout session
  • POST /api/billing/portal - Customer portal access
  • POST /api/billing/cancel - Cancel subscription

Rate Limitingโ€‹

  • General Endpoints: 100 requests per minute
  • Authentication: 10 requests per minute
  • File Uploads: 5 requests per minute
  • Billing: 20 requests per minute

Rate limit headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

๐Ÿ”„ WebSocket APIโ€‹

Connection Establishmentโ€‹

The WebSocket handshake is authenticated with the same JWT used for the REST API. The browser automatically attaches the access token cookie set by /login (or /register / /oauth2/discord); native clients can use Authorization: Bearer <token> instead.

const ws = new WebSocket('wss://api.pianorhythm.io/api/websocket');

Message Formatโ€‹

All WebSocket messages use Protocol Buffers for efficient serialization:

message ServerMessage {
ServerMessageType messageType = 1;
oneof message {
CreateRoomCommand createRoomCommand = 2;
JoinRoomCommand joinRoomCommand = 3;
ChatMessage chatMessage = 4;
MidiMessage midiMessage = 5;
// ... other message types
}
}

Message Typesโ€‹

  • Room Management - Create, join, leave rooms
  • Chat Messages - Text communication
  • MIDI Messages - Musical note data
  • User Commands - Avatar, settings, etc.
  • System Messages - Heartbeat, errors, notifications

Connection Lifecycleโ€‹

  1. Connection - WebSocket established
  2. Authentication - User credentials validated
  3. Session Start - User session initialized
  4. Message Exchange - Bidirectional communication
  5. Heartbeat - Keep-alive mechanism
  6. Disconnection - Graceful or unexpected closure

๐Ÿ“Š Data Modelsโ€‹

User Modelโ€‹

{
"user_id": "uuid",
"username": "string",
"user_tag": "string",
"email": "string",
"roles": ["string"],
"is_member": "boolean",
"is_pro": "boolean",
"avatar_url": "string",
"created_at": "datetime",
"last_seen": "datetime"
}

Room Modelโ€‹

{
"room_id": "string",
"room_name": "string",
"room_owner": "string",
"room_type": "public|private|pro",
"max_users": "number",
"current_users": "number",
"has_password": "boolean",
"created_at": "datetime",
"settings": {
"allow_chat": "boolean",
"allow_guests": "boolean",
"auto_moderation": "boolean"
}
}

Chat Message Modelโ€‹

{
"message_id": "string",
"user_id": "string",
"username": "string",
"message": "string",
"timestamp": "datetime",
"message_type": "user|system|bot"
}

๐Ÿ” Error Handlingโ€‹

HTTP Status Codesโ€‹

  • 200 OK - Successful operation
  • 201 Created - Resource created successfully
  • 400 Bad Request - Invalid request parameters
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Insufficient permissions
  • 404 Not Found - Resource not found
  • 429 Too Many Requests - Rate limit exceeded
  • 500 Internal Server Error - Server error

Error Categoriesโ€‹

  • Validation Errors - Invalid input data
  • Authentication Errors - Login/token issues
  • Authorization Errors - Permission denied
  • Resource Errors - Not found or unavailable
  • Rate Limit Errors - Too many requests
  • Server Errors - Internal system issues

Error Response Examplesโ€‹

{
"success": false,
"error": {
"code": "ROOM_NOT_FOUND",
"message": "The specified room does not exist",
"details": {
"room_id": "invalid_room_123"
}
}
}

๐Ÿ“ˆ API Versioningโ€‹

Version Strategyโ€‹

  • URL Versioning - /api/v1/endpoint
  • Header Versioning - API-Version: v1
  • Backward Compatibility - Maintain previous versions

Current Versionsโ€‹

  • v1 - Current stable version
  • v2 - (Future) Enhanced features

๐Ÿ”ง SDK and Librariesโ€‹

Official SDKsโ€‹

  • JavaScript/TypeScript - Web and Node.js
  • C# - Unity and .NET applications
  • Python - Server integrations
  • Rust - High-performance clients

Community Librariesโ€‹

  • React Hooks - React integration
  • Vue Composables - Vue.js integration
  • Angular Services - Angular integration

๐Ÿ“Š API Monitoringโ€‹

Metrics Trackedโ€‹

  • Request Volume - Requests per second/minute
  • Response Times - Average and percentile latencies
  • Error Rates - Error percentage by endpoint
  • Authentication Success - Login success rates

Health Endpointsโ€‹

  • GET /health - Basic health check
  • GET /health/detailed - Comprehensive system status
  • GET /metrics - Prometheus metrics endpoint

๐Ÿ”ฎ Future API Featuresโ€‹

Planned Enhancementsโ€‹

  • GraphQL API - Flexible query interface
  • Webhook Support - Event notifications
  • Batch Operations - Multiple operations in single request
  • Real-time Subscriptions - Server-sent events

API Evolutionโ€‹

  • Breaking Changes - Communicated 90 days in advance
  • Deprecation Policy - 6-month deprecation period
  • Migration Guides - Detailed upgrade instructions

For detailed endpoint documentation, see: