# Integrations & API Access

BLOB's value extends beyond its direct monitoring capabilities through comprehensive integration options and API access that allow the collected data to flow seamlessly into existing port management systems and third-party applications. This interoperability transforms BLOB from a standalone monitoring solution into a core component of integrated port intelligence infrastructure.

## External System Integrations

BLOB is built with interoperability at its core, ensuring seamless integration with key external systems used in port and coastal management.

It directly integrates with the **OPTICS** system at the Port of Corpus Christi, feeding real-time bathymetry and current data to support vessel traffic and berth allocation. This allows port staff to access BLOB’s insights within their existing interface, streamlining operations without needing to manage separate tools.

BLOB is also compatible with **NOAA PORTS®**, enhancing this nationwide sensor network with mobile, high-resolution data that fills spatial gaps between fixed stations. This collaboration improves the overall accuracy and scope of environmental monitoring.

In support of **dredging operations**, BLOB interfaces with dredge management dashboards, providing detailed bathymetry data to inform dredging priorities and assess post-operation results. This helps optimize sediment management and maintenance planning.

These integration capabilities make BLOB a powerful, cooperative tool within existing port infrastructure, enhancing situational awareness and operational efficiency.

## API Architecture

BLOB’s API is built on RESTful principles, offering a clear and structured interface for accessing both real-time and historical data. It organizes data by resource types—such as bathymetry, water quality, or current patterns—with standardized endpoints for each category.

Security is managed through **OAuth 2.0**, enabling secure, controlled access with API keys managed via an admin portal. This portal allows for easy credential management, including key creation, revocation, and usage tracking.

To ensure stability and fairness, **rate limiting and usage quotas** are enforced, with customizable thresholds based on operational needs or partner agreements. This design makes the API robust, scalable, and easy to integrate with external systems.

## API Functions

The BLOB API provides three primary categories of functionality: live stream access, historical query endpoints, and predictive event notifications.

### Live Stream Access

Live stream endpoints provide near-real-time access to data as it's collected by BLOB during active missions. These streams use WebSocket connections to push updates to subscribed clients with minimal latency, supporting applications that require immediate awareness of changing conditions.

```javascript
// Example: Connecting to BLOB live data stream
const socket = new WebSocket('wss://api.blob-system.com/v1/streams/environmental');

socket.onopen = function(event) {
  console.log('Connection established');
  
  // Subscribe to specific parameters
  socket.send(JSON.stringify({
    action: 'subscribe',
    parameters: ['water_temperature', 'turbidity', 'dissolved_oxygen'],
    area: {
      lat1: 27.8279, 
      lon1: -97.0942,
      lat2: 27.8102, 
      lon2: -97.0703
    }
  }));
};

socket.onmessage = function(event) {
  const data = JSON.parse(event.data);
  console.log('Live data received:', data);
  
  // Process incoming data
  updateDashboard(data);
};
```

The live stream API supports filtering by geographic area, parameter types, and threshold values, allowing clients to receive only the specific data relevant to their needs rather than processing the entire data stream.

### Historical Query Endpoints

Historical query endpoints provide access to archived data, supporting analysis of trends, comparison with current conditions, and research applications. These endpoints implement a flexible query language that allows clients to specify precise criteria for the data they wish to retrieve.

```python
# Example: Querying historical bathymetry data
import requests
import json
import pandas as pd
from datetime import datetime, timedelta

# Set API credentials
api_key = 'your_api_key'
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}

# Define query parameters
end_date = datetime.now()
start_date = end_date - timedelta(days=30)

query_params = {
    'parameter': 'bathymetry',
    'start_time': start_date.isoformat(),
    'end_time': end_date.isoformat(),
    'area': {
        'lat1': 27.8279, 
        'lon1': -97.0942,
        'lat2': 27.8102, 
        'lon2': -97.0703
    },
    'resolution': 'high',
    'format': 'json'
}

# Make API request
response = requests.post(
    'https://api.blob-system.com/v1/query/historical',
    headers=headers,
    data=json.dumps(query_params)
)

# Process response
if response.status_code == 200:
    data = response.json()
    
    # Convert to pandas DataFrame for analysis
    df = pd.DataFrame(data['readings'])
    
    # Calculate average depth change
    avg_change = df['current_depth'].mean() - df['baseline_depth'].mean()
    print(f"Average depth change over past 30 days: {avg_change:.2f} meters")
    
    # Save to CSV for further analysis
    df.to_csv('bathymetry_30day_analysis.csv', index=False)
else:
    print(f"Error: {response.status_code}")
    print(response.text)
```

The historical query API supports various output formats including JSON, CSV, and GeoJSON, accommodating different client requirements and use cases. Pagination options allow efficient retrieval of large datasets without overwhelming client applications or network connections.

### Predictive Event Notifications

Predictive event endpoints leverage BLOB's AI capabilities to provide forward-looking notifications about potential conditions of interest. Rather than simply reporting current or past measurements, these endpoints notify subscribers about predicted events before they occur, enabling proactive management.

```javascript
// Example: Subscribing to predictive sediment events
const axios = require('axios');

async function subscribeToPredictiveEvents() {
  try {
    const response = await axios.post('https://api.blob-system.com/v1/events/subscribe', {
      event_types: ['sediment_accumulation', 'scour_risk'],
      threshold: 'medium',
      notification_channels: [
        {
          type: 'webhook',
          endpoint: 'https://your-system.com/api/blob-notifications',
          headers: {
            'X-API-Key': 'your_webhook_secret'
          }
        },
        {
          type: 'email',
          address: 'operations@port.example.com'
        }
      ],
      area_of_interest: {
        lat1: 27.8279, 
        lon1: -97.0942,
        lat2: 27.8102, 
        lon2: -97.0703
      }
    }, {
      headers: {
        'Authorization': 'Bearer your_api_key',
        'Content-Type': 'application/json'
      }
    });
    
    console.log('Subscription created:', response.data);
    return response.data.subscription_id;
  } catch (error) {
    console.error('Error creating subscription:', error.response ? error.response.data : error.message);
  }
}

// Example webhook handler for receiving notifications
const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/blob-notifications', (req, res) => {
  const event = req.body;
  
  console.log('Received predictive event:', event);
  
  // Process the event (e.g., create work order, alert staff)
  if (event.type === 'sediment_accumulation' && event.confidence > 0.8) {
    createDredgingWorkOrder(event.location, event.predicted_volume);
  }
  
  res.status(200).send('Event received');
});

app.listen(3000, () => console.log('Notification receiver running on port 3000'));
```

The predictive event API supports multiple notification channels including webhooks, email, SMS, and integration with common messaging platforms. Subscribers can specify thresholds for notification, ensuring they receive alerts only for events that meet their criteria for significance.

## Developer Resources

To support seamless integration, BLOB offers a robust set of developer resources alongside its RESTful API. The **API documentation** is built on the OpenAPI (Swagger) specification, offering both interactive, browser-based tools for testing requests and machine-readable formats for auto-generating client code.

**Client libraries** are available for Python, JavaScript, Java, and C#, simplifying integration across common environments by managing authentication, data handling, and error processing.

**Sample applications** with full source code demonstrate typical use cases like dashboard integration, automated reporting, and alerting—giving developers practical starting points they can tailor to specific needs.

These resources make BLOB highly interoperable, enabling it to function not just as a standalone system, but as an integral part of a larger port intelligence ecosystem—enhancing situational awareness, automation, and decision-making across operations.
