CHAPTER 5

Phase 2 - API Interface

Building on the standardized data formats established in Phase 1, Phase 2 provides computational services and APIs that make biodiversity data actionable. This chapter details the RESTful and GraphQL APIs, diversity calculation engines, integration services, and real-time analytics capabilities that transform raw observations into meaningful conservation insights.

API Architecture

The WIA API follows modern REST principles while offering GraphQL for complex queries. This dual approach balances simplicity for basic operations with power for advanced use cases.

RESTful Endpoints

The REST API organizes resources hierarchically and uses standard HTTP methods. Host names used in this chapter's examples (such as api.biodiversity.wia.org) and the SDK package name are illustrative reference-implementation names, not live public services or published packages:

Base URL: https://api.biodiversity.wia.org/v1/

# Occurrence endpoints
GET    /occurrences                    # List occurrences (paginated)
POST   /occurrences                    # Create new occurrence
GET    /occurrences/{id}              # Get specific occurrence
PUT    /occurrences/{id}              # Update occurrence
DELETE /occurrences/{id}              # Delete occurrence

# Diversity indices
POST   /indices/calculate              # Calculate diversity indices
GET    /indices/{calculation_id}       # Retrieve calculated indices
GET    /indices/trends                 # Temporal trend analysis

# Species endpoints
GET    /species                        # List species
GET    /species/{taxon_id}            # Get species details
GET    /species/{taxon_id}/occurrences # Occurrences for species
GET    /species/search?q={query}      # Search species

# Spatial queries
GET    /spatial/region/{polygon}       # Occurrences in polygon
GET    /spatial/proximity              # Species near coordinates
POST   /spatial/hotspots              # Identify biodiversity hotspots

# Data validation
POST   /validate/occurrence            # Validate occurrence data
POST   /validate/batch                # Batch validation

# Integration
POST   /export/gbif                    # Export to GBIF format
POST   /export/geojson                # Export as GeoJSON
GET    /taxonomy/resolve              # Resolve taxonomic names

Authentication and Authorization

The API uses OAuth 2.0 with JWT tokens for secure, stateless authentication:

# Obtain access token
POST https://auth.biodiversity.wia.org/oauth/token
Content-Type: application/json

{
  "grant_type": "client_credentials",
  "client_id": "your_client_id",
  "client_secret": "your_client_secret",
  "scope": "read:occurrences write:occurrences calculate:indices"
}

# Response
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read:occurrences write:occurrences calculate:indices"
}

# Use token in requests
GET https://api.biodiversity.wia.org/v1/occurrences
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

Diversity Index Calculation API

The core analytical capability - calculating biodiversity indices from occurrence data:

Calculate Diversity Indices

POST /v1/indices/calculate
Content-Type: application/json
Authorization: Bearer {token}

{
  "dataset_id": "DS-AMAZON-2025",
  "spatial_filter": {
    "type": "polygon",
    "coordinates": [[[-60.5, -3.5], [-60.0, -3.5], [-60.0, -3.0], [-60.5, -3.0], [-60.5, -3.5]]]
  },
  "temporal_filter": {
    "start_date": "2025-01-01",
    "end_date": "2025-12-31"
  },
  "indices": [
    "species_richness",
    "shannon_diversity",
    "simpson_index",
    "pielou_evenness"
  ],
  "rarefaction": {
    "enabled": true,
    "target_n": 1000
  },
  "bootstrap": {
    "enabled": true,
    "iterations": 1000,
    "confidence_level": 0.95
  }
}

# Response
{
  "calculation_id": "CALC-2025-AZ-1234",
  "status": "completed",
  "execution_time_ms": 2847,
  "results": {
    "species_richness": {
      "observed": 156,
      "rarefied": 142.7,
      "ci_lower": 138.2,
      "ci_upper": 147.3
    },
    "shannon_diversity": {
      "value": 4.127,
      "ci_lower": 3.982,
      "ci_upper": 4.268
    },
    "simpson_index": {
      "value": 0.0234,
      "diversity_1_minus_d": 0.9766,
      "inverse": 42.74
    },
    "pielou_evenness": {
      "value": 0.817,
      "interpretation": "high_evenness"
    }
  },
  "metadata": {
    "input_occurrences": 4523,
    "unique_species": 156,
    "total_individuals": 8947,
    "calculation_date": "2025-12-26T10:30:00Z"
  }
}

GraphQL Interface

For complex queries requiring multiple related resources, GraphQL provides efficient single-request access:

POST https://api.biodiversity.wia.org/graphql
Content-Type: application/json

{
  "query": "{
    species(scientificName: \"Panthera tigris\") {
      taxonId
      commonNames
      conservationStatus {
        category
        populationTrend
      }
      occurrences(limit: 10, year: 2025) {
        occurrenceId
        location {
          latitude
          longitude
          protectedArea
        }
        observationDate
        individualCount
      }
      diversityIndices(region: \"India\") {
        shannonIndex
        simpsonIndex
      }
    }
  }"
}

# Response provides exactly requested data structure
{
  "data": {
    "species": {
      "taxonId": "WIA-TAX-001200",
      "commonNames": ["Tiger", "बाघ"],
      "conservationStatus": {
        "category": "EN",
        "populationTrend": "Increasing"
      },
      "occurrences": [
        {
          "occurrenceId": "OCC-2025-IN-78945",
          "location": {
            "latitude": 27.5142,
            "longitude": 88.7597,
            "protectedArea": true
          },
          "observationDate": "2025-11-15",
          "individualCount": 1
        }
        // ... more occurrences
      ],
      "diversityIndices": {
        "shannonIndex": 3.45,
        "simpsonIndex": 0.0412
      }
    }
  }
}

Real-Time Analytics

WebSocket connections enable real-time biodiversity monitoring and alerts:

// Connect to WebSocket
const ws = new WebSocket('wss://stream.biodiversity.wia.org/v1/live');

// Subscribe to endangered species detections
ws.send(JSON.stringify({
  "action": "subscribe",
  "channels": ["endangered_detections"],
  "filters": {
    "region": "Southeast_Asia",
    "iucn_categories": ["CR", "EN"]
  }
}));

// Receive real-time alerts
ws.onmessage = (event) => {
  const alert = JSON.parse(event.data);
  console.log('Endangered species detected:', alert);
  /*
  {
    "event_type": "endangered_detection",
    "timestamp": "2025-12-26T14:23:15Z",
    "species": {
      "scientific_name": "Dicerorhinus sumatrensis",
      "common_name": "Sumatran Rhino",
      "iucn_status": "CR"
    },
    "location": {
      "latitude": -4.9300,
      "longitude": 105.7800,
      "protected_area": "Way Kambas National Park"
    },
    "detection_method": "camera_trap",
    "confidence": 0.96
  }
  */
};

Data Validation Services

Automated validation ensures data quality before submission:

POST /v1/validate/occurrence

{
  "occurrence_id": "OCC-2025-TEST-001",
  "species": {
    "scientific_name": "Panthera tigris",
    "taxon_id": "GBIF:5219416"
  },
  "location": {
    "latitude": 27.5142,
    "longitude": 88.7597,
    "country": "India"
  },
  "temporal": {
    "observation_date": "2025-11-15T09:30:00Z"
  }
}

# Response
{
  "valid": true,
  "quality_score": 0.94,
  "checks": [
    {
      "check": "coordinate_validity",
      "status": "passed",
      "message": "Coordinates within valid range"
    },
    {
      "check": "country_match",
      "status": "passed",
      "message": "Coordinates match stated country (India)"
    },
    {
      "check": "species_range",
      "status": "passed",
      "message": "Location within known species range"
    },
    {
      "check": "taxonomy_valid",
      "status": "passed",
      "message": "Taxon ID resolves to valid GBIF entry"
    },
    {
      "check": "date_reasonable",
      "status": "passed",
      "message": "Date not in future, within reasonable historical range"
    }
  ],
  "warnings": [],
  "errors": []
}

Integration Services

GBIF Upload Service

Direct submission to Global Biodiversity Information Facility:

POST /v1/export/gbif

{
  "dataset_id": "DS-AMAZON-2025",
  "gbif_dataset_key": "50c9509d-22c7-4a22-a47d-8c48425ef4a7",
  "filters": {
    "date_range": {
      "start": "2025-01-01",
      "end": "2025-12-31"
    }
  },
  "mapping_profile": "darwin_core_v1.0",
  "validate_before_upload": true
}

# Response
{
  "export_id": "EXP-GBIF-2025-1234",
  "status": "processing",
  "records_to_export": 4523,
  "validation_results": {
    "valid": 4498,
    "warnings": 25,
    "errors": 0
  },
  "estimated_completion": "2025-12-26T15:00:00Z"
}

IUCN Red List Integration

Retrieve conservation status and threat information. The assessment criteria, population trend, threats, conservation actions, and assessment date in the response below are example values that illustrate the response format; actual values follow the latest IUCN Red List assessment.

GET /v1/integration/iucn/species/Panthera%20tigris

# Response
{
  "scientific_name": "Panthera tigris",
  "category": "EN",
  "criteria": "A2abcd+3cd+4abcd",
  "population_trend": "Increasing",
  "systems": ["Terrestrial"],
  "threats": [
    {
      "code": "5.1.1",
      "title": "Intentional use (species is the target)",
      "timing": "Ongoing",
      "scope": "Minority (<50%)",
      "severity": "Rapid Declines",
      "score": "Medium Impact: 6"
    },
    {
      "code": "2.1.2",
      "title": "Small-holder farming",
      "timing": "Ongoing",
      "scope": "Majority (50-90%)",
      "severity": "Slow, Significant Declines",
      "score": "Medium Impact: 7"
    }
  ],
  "conservation_actions": [
    {
      "code": "2.1",
      "title": "Site/area management"
    },
    {
      "code": "4.3",
      "title": "Awareness & communications"
    }
  ],
  "source": "IUCN Red List API v3",
  "assessment_date": "2023-06-15"
}

Rate Limiting and Performance

To ensure fair access and system stability, the API implements rate limiting:

Tier Rate Limit Burst Limit Use Case
Free 1,000 req/hour 50 req/minute Individual researchers, small projects
Research 10,000 req/hour 200 req/minute Academic institutions, NGOs
Enterprise 100,000 req/hour 1,000 req/minute Government agencies, large conservation orgs
Custom Negotiable Negotiable Global initiatives, long-term partnerships

SDK and Client Libraries

Official SDKs simplify API integration across programming languages:

Python SDK Example

from wia_biodiversity import BiodiversityAPI

# Initialize client
client = BiodiversityAPI(api_key='your_api_key')

# Query occurrences
occurrences = client.occurrences.list(
    species='Panthera tigris',
    country='India',
    year=2025,
    limit=100
)

# Calculate diversity indices
results = client.indices.calculate(
    dataset_id='DS-INDIA-2025',
    indices=['shannon', 'simpson', 'richness'],
    spatial_filter=client.geo.polygon([
        [88.0, 27.0], [89.0, 27.0], [89.0, 28.0], [88.0, 28.0]
    ]),
    bootstrap_iterations=1000
)

print(f"Shannon Diversity: {results.shannon.value:.3f}")
print(f"Species Richness: {results.richness.observed}")

TypeScript SDK Example

import { BiodiversityClient } from '@wia/biodiversity-sdk';

const client = new BiodiversityClient({
  apiKey: process.env.WIA_API_KEY
});

// Real-time species detection monitoring
const stream = client.stream.subscribe({
  channels: ['endangered_detections'],
  filters: {
    region: 'Southeast_Asia',
    iucnCategories: ['CR', 'EN']
  }
});

stream.on('detection', (event) => {
  console.log(`${event.species.commonName} detected!`);
  console.log(`Location: ${event.location.protectedArea}`);
  console.log(`Confidence: ${event.confidence}`);
});

Error Handling

The API uses standard HTTP status codes and structured error responses:

# Error response format
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid species name format",
    "details": {
      "field": "species.scientific_name",
      "value": "panthera tigris",  // lowercase - invalid
      "expected": "Capitalized binomial nomenclature"
    },
    "documentation_url": "https://docs.biodiversity.wia.org/errors/VALIDATION_ERROR"
  },
  "request_id": "req_abc123def456"
}
Status Code Error Code Description
400 VALIDATION_ERROR Request data fails validation rules
401 UNAUTHORIZED Missing or invalid authentication
403 FORBIDDEN Valid auth but insufficient permissions
404 NOT_FOUND Requested resource doesn't exist
429 RATE_LIMIT_EXCEEDED Too many requests
500 INTERNAL_ERROR Server-side processing error

Chapter Summary

Key Takeaways

  • Dual API approach - RESTful endpoints for simple operations, GraphQL for complex queries, providing both ease of use and power.
  • Comprehensive analytical services - Automated diversity index calculation with bootstrap confidence intervals and rarefaction support.
  • Real-time capabilities - WebSocket streaming enables live monitoring and instant alerts for conservation priorities.
  • Seamless integration - Built-in connectors for GBIF, IUCN, and other major biodiversity platforms eliminate manual data transfer.
  • Production-ready features - OAuth 2.0 authentication, rate limiting, error handling, and official SDKs ensure enterprise-grade reliability.

Review Questions

  1. Compare REST and GraphQL approaches in the WIA API. When would you choose each for a biodiversity monitoring application?
  2. Explain how the diversity index calculation API handles statistical uncertainty through bootstrap and rarefaction methods.
  3. Describe the authentication flow using OAuth 2.0. Why is this approach more secure than API key-only authentication?
  4. How do WebSocket streams enable real-time conservation responses that traditional polling cannot?
  5. What validation checks are performed before data submission? How does this prevent data quality issues downstream?
  6. Discuss the rate limiting tiers. How do they balance open access principles with system sustainability?

Looking Ahead: Chapter 6 presents Phase 3: Protocol, detailing standardized field survey methodologies, quality assurance procedures, and certification programs that ensure data quality from the point of collection.