Chapter 5: Phase 2 - API Interface

The API Interface layer is the nervous system of the WIA-CONTACT-001 architecture, enabling real-time communication between observatories, analysis centers, verification networks, and coordination hubs across the globe. This chapter provides comprehensive documentation of the RESTful API endpoints, WebSocket streaming protocols, authentication mechanisms, error handling patterns, and SDK usage. Whether you are building a detection pipeline, verification service, or analysis tool, this chapter provides everything needed to achieve full interoperability with the WIA-CONTACT-001 network.

The API design follows modern best practices: REST principles for resource manipulation, WebSocket for real-time streaming, OAuth 2.0 for authentication, and JSON for data exchange. Rate limiting, pagination, and caching are built into the specification to ensure scalability and fair resource allocation across the global network of participating systems.

5.1 API Design Philosophy

The WIA-CONTACT-001 API is designed around several core principles that ensure consistency, predictability, and ease of use across all endpoints:

Resource-Oriented Design: The API exposes resources (signals, verifications, analyses, facilities) through predictable URL patterns. Each resource has standard operations (create, read, update, delete) mapped to HTTP methods (POST, GET, PUT, DELETE). This predictability reduces learning curve and enables generic client implementations.

Statelessness: Each request contains all information needed for processing. Servers maintain no session state between requests, enabling horizontal scaling across multiple server instances. This is critical for a global system that must handle sudden load spikes during detection events.

Idempotency: Repeated identical requests produce the same result. This is essential for reliability in distributed systems where network failures may cause request duplication. PUT and DELETE operations are inherently idempotent; POST operations use client-generated request IDs to enable idempotency.

Versioning: The API version is included in the URL path (/v1/...), enabling smooth evolution while maintaining backward compatibility. Deprecated features are announced with generous sunset periods, ensuring clients have time to migrate.

5.2 RESTful Endpoints

5.2.1 Signal Detection Endpoints

Table 5.1: Signal Detection API Endpoints
MethodEndpointDescriptionAuth Required
POST/v1/signalsSubmit a new signal detectionYes (detector+)
GET/v1/signalsList signal detections (paginated)Yes (observer+)
GET/v1/signals/{id}Get specific signal detailsYes (observer+)
PUT/v1/signals/{id}Update signal recordYes (owner only)
DELETE/v1/signals/{id}Retract signal detectionYes (owner only)

5.2.2 Submit Signal Detection

POST /v1/signals
Content-Type: application/json
Authorization: Bearer <access_token>
X-Request-ID: req-unique-12345

{
  "signal": {
    "frequency": {
      "center": 1420405751.768,
      "bandwidth": 0.5,
      "unit": "Hz",
      "driftRate": 0.0023
    },
    "power": { "snr": 15.7, "flux": 1.2e-26 },
    "modulation": { "type": "narrowband" }
  },
  "source": {
    "position": {
      "ra": "19h25m12.34s",
      "dec": "+21d45m32.1s",
      "frame": "ICRS"
    },
    "uncertainty": { "ra": 0.5, "dec": 0.5, "unit": "arcsec" }
  },
  "temporal": {
    "detected": "2025-12-29T14:25:33.123Z",
    "duration": 72.5
  }
}

Response: 201 Created
Location: /v1/signals/sdr:2025-12-29-GBT-001
{
  "id": "sdr:2025-12-29-GBT-001",
  "status": "unverified",
  "created": "2025-12-29T14:30:00Z",
  "links": {
    "self": "/v1/signals/sdr:2025-12-29-GBT-001",
    "verification": "/v1/signals/sdr:2025-12-29-GBT-001/verification",
    "facility": "/v1/facilities/GBT"
  }
}
        

5.2.3 Verification Endpoints

Table 5.2: Verification API Endpoints
MethodEndpointDescription
POST/v1/signals/{id}/verificationRequest verification campaign
GET/v1/signals/{id}/verificationGet verification status and history
POST/v1/signals/{id}/verification/observationsSubmit verification observation result
GET/v1/verificationsList all verification requests (paginated)
GET/v1/verifications/pendingList pending verification requests for facility

5.3 Authentication and Authorization

The API uses OAuth 2.0 with JWT (JSON Web Tokens) for authentication. This industry-standard approach provides secure, stateless authentication suitable for distributed systems while supporting multiple client types from automated pipelines to interactive dashboards.

5.3.1 Authentication Flow

# 1. Request access token using client credentials
POST /v1/auth/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&
client_id=gbt-detection-system&
client_secret=<secret>&
scope=signals:write verifications:read

# 2. Response with JWT token
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "signals:write verifications:read",
  "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4..."
}

# 3. Use token in subsequent requests
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
        

5.3.2 Role-Based Access Control

Permissions are organized into roles that can be assigned to authenticated entities. Roles follow a hierarchy where higher roles include all permissions of lower roles:

Table 5.3: API Roles and Permissions
RolePermissionsDescription
observersignals:read, verifications:readRead-only access to public signals
detector+ signals:writeSubmit and manage own detections
verifier+ verifications:writeParticipate in verification campaigns
analyst+ analyses:*Perform and publish signal analyses
coordinator+ admin:*Full system access, regional coordination

5.4 WebSocket Real-Time Streaming

For time-critical operations, the API provides WebSocket connections for real-time event streaming. This is essential for rapid alert propagation during detection events, where minutes or even seconds can matter.

5.4.1 Connection and Subscription

// Connect to alert stream
const ws = new WebSocket('wss://api.wia-contact.org/v1/stream');

// Authenticate immediately after connection
ws.onopen = () => {
  ws.send(JSON.stringify({
    type: 'authenticate',
    token: accessToken
  }));
};

// Subscribe to relevant channels after authentication
ws.send(JSON.stringify({
  type: 'subscribe',
  channels: ['alerts', 'verifications', 'facility:GBT']
}));

// Handle incoming events
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);

  switch(data.type) {
    case 'new_detection':
      console.log('New signal detected:', data.signal.id);
      handleNewDetection(data.signal);
      break;

    case 'verification_requested':
      console.log('Verification request:', data.verification);
      scheduleVerificationObservation(data.verification);
      break;

    case 'status_change':
      console.log('Signal status updated:', data.signalId, data.newStatus);
      updateLocalDatabase(data);
      break;
  }
};
        

5.4.2 Event Types

Table 5.4: WebSocket Event Types
EventChannelDescriptionPayload
new_detectionalertsNew signal detection submittedFull SDR
verification_requestedverificationsVerification campaign initiatedRequest details
verification_observationverificationsNew observation resultObservation data
status_changealertsSignal status updatedSignal ID, old/new status
threat_assessmentsecurityThreat level determinedAssessment report

5.5 Error Handling

The API uses standard HTTP status codes with detailed error responses. Error responses include machine-readable codes for programmatic handling and human-readable messages for debugging:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "signal.frequency.center",
        "issue": "Value must be positive",
        "received": -1420405751
      },
      {
        "field": "source.position.dec",
        "issue": "Invalid declination format",
        "received": "91d00m00s"
      }
    ],
    "requestId": "req-abc123def456",
    "timestamp": "2025-12-29T14:30:00Z",
    "documentation": "https://docs.wia-contact.org/errors/VALIDATION_ERROR"
  }
}
        
Table 5.5: HTTP Status Codes
CodeMeaningClient Action
200SuccessProcess response normally
201CreatedResource created, check Location header
400Bad RequestFix request data per error details
401UnauthorizedRefresh token or re-authenticate
403ForbiddenInsufficient permissions for operation
404Not FoundResource doesn't exist, check ID
429Too Many RequestsRate limit exceeded, backoff and retry
500Server ErrorReport issue, retry with backoff

5.6 Rate Limiting and Quotas

To ensure fair resource allocation across the global network, the API implements rate limiting. Limits vary by role and adjust dynamically based on system load:

Rate limit information is returned in response headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 847
X-RateLimit-Reset: 1703863860
X-RateLimit-Policy: detector-standard
        

5.7 SDK Overview

5.7.1 TypeScript SDK

import { WIAContactClient } from '@wia/contact-sdk';

const client = new WIAContactClient({
  apiKey: process.env.WIA_API_KEY,
  facility: 'GBT',
  environment: 'production'
});

// Submit detection
const signal = await client.signals.create({
  frequency: { center: 1420405751.768, bandwidth: 0.5 },
  power: { snr: 15.7 },
  source: { ra: '19h25m12.34s', dec: '+21d45m32.1s' },
  detected: new Date()
});

console.log(`Signal submitted: ${signal.id}`);

// Request verification
const verification = await client.verifications.request(signal.id, {
  priority: 'high',
  targetObservatories: ['Parkes', 'Effelsberg', 'Arecibo']
});

// Subscribe to real-time updates
client.stream.subscribe('alerts', (event) => {
  console.log('Alert:', event.type, event.data);
});
        

5.7.2 Python SDK

from wia_contact import WIAContactClient
import os

client = WIAContactClient(
    api_key=os.environ['WIA_API_KEY'],
    facility='GBT'
)

# Submit detection
signal = client.signals.create(
    frequency={'center': 1420405751.768, 'bandwidth': 0.5},
    power={'snr': 15.7},
    source={'ra': '19h25m12.34s', 'dec': '+21d45m32.1s'},
    detected=datetime.utcnow()
)

print(f"Signal submitted: {signal.id}")

# Query signals by position
nearby = client.signals.search(
    ra=290.5, dec=21.7,
    radius=1.0,
    unit='deg',
    status='verified'
)

for s in nearby:
    print(f"  {s.id}: {s.frequency.center} Hz, SNR={s.power.snr}")
        
Best Practice: Always use the official SDK rather than making raw HTTP requests. The SDK handles authentication refresh, rate limiting with automatic backoff, retry logic for transient failures, and error handling automatically. It also validates requests locally before submission, reducing API errors.

Chapter 5 Summary

Key Takeaways:

  1. API Design: RESTful design with resource-oriented endpoints, stateless operation, and semantic versioning enables predictable, scalable interactions across the global network.
  2. Authentication: OAuth 2.0 with JWT provides secure, standards-based authentication. Role-based access control enables fine-grained permissions.
  3. Real-Time Communication: WebSocket connections enable real-time event streaming for time-critical alert propagation during detection events.
  4. Error Handling: Standardized error responses with codes, messages, and details enable effective debugging and programmatic error recovery.
  5. Rate Limiting: Fair resource allocation through role-based rate limits ensures system stability during peak loads.
  6. SDKs: Official SDKs for TypeScript and Python simplify integration and handle common concerns automatically.

Review Questions

  1. Explain the RESTful design principles used in the WIA-CONTACT-001 API. Why is each principle important for a global distributed system?
  2. Describe the OAuth 2.0 authentication flow. Why is token-based authentication preferred over session-based for this use case?
  3. Compare REST API and WebSocket communication. Under what circumstances should each be used?
  4. Design a client application that monitors for new detections and automatically requests verification. What API calls would it make?
  5. How does rate limiting ensure fair resource allocation? What should a client do when limits are exceeded?
  6. Write code using the SDK to submit a signal detection, request verification, and monitor for status updates.

Looking Ahead

Chapter 6 will explore Phase 3: Protocol specifications. We will examine the operational procedures for detection, verification cascade, threat assessment, and response coordination that govern how the system responds to potential first contact scenarios.