> ## Documentation Index
> Fetch the complete documentation index at: https://docs.terraquakeapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDKs & Libraries

> Client libraries and code examples for integrating TerraQuake API

## Official SDKs

> [!NOTE]
>
> **Coming Soon**: Official SDKs for popular programming languages are currently in development.
>
> We welcome community contributions! If you'd like to help build an official SDK, please visit our [GitHub repository](https://github.com/nagcas/TerraQuakeApi).

## Using the REST API

TerraQuake API is a standard RESTful API that returns JSON responses. You can use any HTTP client library in your preferred programming language.

### JavaScript / TypeScript

#### Using Fetch (Native)

```javascript theme={null}
// Fetch recent earthquakes
const response = await fetch(
  'https://api.terraquakeapi.com/v1/earthquakes/recent?limit=10&page=1'
);
const data = await response.json();

if (data.success) {
  console.log(`Found ${data.totalEarthquakes} earthquakes`);
  data.payload.forEach(earthquake => {
    const { mag, place, time } = earthquake.properties;
    const [lon, lat, depth] = earthquake.geometry.coordinates;
    console.log(`Magnitude ${mag} at ${place} (${lat}, ${lon})`);
  });
}
```

#### Using Axios

```javascript theme={null}
import axios from 'axios';

const client = axios.create({
  baseURL: 'https://api.terraquakeapi.com/v1',
  timeout: 10000,
});

// Get earthquakes by magnitude
const getEarthquakesByMagnitude = async (magnitude) => {
  try {
    const response = await client.get('/earthquakes/magnitude', {
      params: { mag: magnitude, limit: 50 }
    });
    return response.data.payload;
  } catch (error) {
    console.error('Error fetching earthquakes:', error.message);
    throw error;
  }
};

// Usage
const strongEarthquakes = await getEarthquakesByMagnitude(4.0);
```

### Python

#### Using Requests

```python theme={null}
import requests
from datetime import datetime, timedelta

BASE_URL = 'https://api.terraquakeapi.com/v1'

def get_recent_earthquakes(limit=50, page=1):
    """Fetch recent earthquakes from TerraQuake API."""
    response = requests.get(
        f'{BASE_URL}/earthquakes/recent',
        params={'limit': limit, 'page': page}
    )
    response.raise_for_status()
    return response.json()

def get_earthquakes_by_region(region, limit=50):
    """Fetch earthquakes for a specific Italian region."""
    response = requests.get(
        f'{BASE_URL}/earthquakes/region',
        params={'region': region, 'limit': limit}
    )
    response.raise_for_status()
    data = response.json()
    
    if data['success']:
        return data['payload']
    else:
        raise Exception(f"API Error: {data.get('message', 'Unknown error')}")

# Usage
try:
    earthquakes = get_recent_earthquakes(limit=10)
    print(f"Total earthquakes: {earthquakes['totalEarthquakes']}")
    
    for event in earthquakes['payload']:
        props = event['properties']
        coords = event['geometry']['coordinates']
        print(f"{props['time']} - M{props['mag']} - {props['place']}")
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")
```

#### Using HTTPX (Async)

```python theme={null}
import httpx
import asyncio

async def fetch_earthquakes_async():
    """Asynchronously fetch earthquake data."""
    async with httpx.AsyncClient() as client:
        response = await client.get(
            'https://api.terraquakeapi.com/v1/earthquakes/today',
            params={'limit': 100}
        )
        return response.json()

# Usage
data = asyncio.run(fetch_earthquakes_async())
print(f"Today's earthquakes: {data['totalEarthquakes']}")
```

### PHP

#### Using cURL

```php theme={null}
<?php

function getTerraQuakeData($endpoint, $params = []) {
    $baseUrl = 'https://api.terraquakeapi.com/v1';
    $url = $baseUrl . $endpoint;
    
    if (!empty($params)) {
        $url .= '?' . http_build_query($params);
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        throw new Exception("API request failed with code: $httpCode");
    }
    
    return json_decode($response, true);
}

// Get earthquakes from last week
$earthquakes = getTerraQuakeData('/earthquakes/last-week', [
    'limit' => 20,
    'page' => 1
]);

if ($earthquakes['success']) {
    foreach ($earthquakes['payload'] as $event) {
        $mag = $event['properties']['mag'];
        $place = $event['properties']['place'];
        echo "Magnitude $mag at $place\n";
    }
}
?>
```

### Ruby

#### Using Net::HTTP

```ruby theme={null}
require 'net/http'
require 'json'
require 'uri'

class TerraQuakeClient
  BASE_URL = 'https://api.terraquakeapi.com/v1'
  
  def self.get_earthquakes(endpoint, params = {})
    uri = URI("#{BASE_URL}#{endpoint}")
    uri.query = URI.encode_www_form(params) unless params.empty?
    
    response = Net::HTTP.get_response(uri)
    
    unless response.is_a?(Net::HTTPSuccess)
      raise "API request failed: #{response.code}"
    end
    
    JSON.parse(response.body)
  end
  
  def self.recent_earthquakes(limit: 50, page: 1)
    get_earthquakes('/earthquakes/recent', { limit: limit, page: page })
  end
  
  def self.earthquakes_by_magnitude(mag, limit: 50)
    get_earthquakes('/earthquakes/magnitude', { mag: mag, limit: limit })
  end
end

# Usage
data = TerraQuakeClient.recent_earthquakes(limit: 10)
puts "Total earthquakes: #{data['totalEarthquakes']}"

data['payload'].each do |event|
  props = event['properties']
  puts "#{props['time']} - M#{props['mag']} - #{props['place']}"
end
```

### Go

```go theme={null}
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "time"
)

type EarthquakeResponse struct {
    Success           bool        `json:"success"`
    Code              int         `json:"code"`
    Message           string      `json:"message"`
    Payload           []Feature   `json:"payload"`
    TotalEarthquakes  int         `json:"totalEarthquakes"`
}

type Feature struct {
    Type       string     `json:"type"`
    Properties Properties `json:"properties"`
    Geometry   Geometry   `json:"geometry"`
}

type Properties struct {
    EventID   int     `json:"eventId"`
    Time      string  `json:"time"`
    Mag       float64 `json:"mag"`
    Place     string  `json:"place"`
    MagType   string  `json:"magType"`
}

type Geometry struct {
    Type        string    `json:"type"`
    Coordinates []float64 `json:"coordinates"`
}

func GetRecentEarthquakes(limit, page int) (*EarthquakeResponse, error) {
    baseURL := "https://api.terraquakeapi.com/v1/earthquakes/recent"
    
    params := url.Values{}
    params.Add("limit", fmt.Sprintf("%d", limit))
    params.Add("page", fmt.Sprintf("%d", page))
    
    fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
    
    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Get(fullURL)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }
    
    var result EarthquakeResponse
    if err := json.Unmarshal(body, &result); err != nil {
        return nil, err
    }
    
    return &result, nil
}

func main() {
    data, err := GetRecentEarthquakes(10, 1)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Total earthquakes: %d\n", data.TotalEarthquakes)
    
    for _, event := range data.Payload {
        fmt.Printf("%s - M%.1f - %s\n",
            event.Properties.Time,
            event.Properties.Mag,
            event.Properties.Place,
        )
    }
}
```

## Best Practices

> **Handle Rate Limiting**
>
> Implement exponential backoff and respect rate limits to avoid throttling.
>
> ```javascript theme={null}
> async function fetchWithRetry(url, maxRetries = 3) {
>   for (let i = 0; i < maxRetries; i++) {
>     const response = await fetch(url);
>
>     if (response.status === 429) {
>       const retryAfter = response.headers.get('Retry-After') || 60;
>       await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
>       continue;
>     }
>
>     return response;
>   }
>   throw new Error('Max retries exceeded');
> }
> ```

> **Error Handling**
>
> Always handle errors gracefully and check the `success` field in responses.
>
> ```python theme={null}
> try:
>     response = requests.get(url)
>     response.raise_for_status()
>     data = response.json()
>
>     if not data.get('success'):
>         print(f"API Error: {data.get('message')}")
> except requests.exceptions.RequestException as e:
>     print(f"Request failed: {e}")
> ```

> **Efficient Pagination**
>
> Use pagination parameters to fetch large datasets efficiently.
>
> ```javascript theme={null}
> async function fetchAllEarthquakes() {
>   const allData = [];
>   let page = 1;
>   let hasMore = true;
>
>   while (hasMore) {
>     const response = await fetch(
>       `https://api.terraquakeapi.com/v1/earthquakes/recent?limit=100&page=${page}`
>     );
>     const data = await response.json();
>
>     allData.push(...data.payload);
>     hasMore = data.pagination.hasMore;
>     page++;
>   }
>
>   return allData;
> }
> ```

> **Cache Responses**
>
> Cache responses when appropriate to reduce API calls and improve performance.
>
> ```python theme={null}
> from functools import lru_cache
> from datetime import datetime, timedelta
>
> @lru_cache(maxsize=100)
> def get_cached_earthquakes(date_key):
>     # Fetch data for a specific date
>     # Cache will persist for the lifetime of the application
>     return fetch_earthquake_data()
> ```

## Community Contributions

We welcome community-built SDKs and client libraries!

> **[Contribute an SDK](https://github.com/nagcas/TerraQuakeApi)**
>
> Build and submit an official SDK for your favorite language

> **[Join Discord](https://discord.gg/RDBp8KJB)**
>
> Discuss SDK development with the community

> [!NOTE]
>
> If you create a client library for TerraQuake API, let us know! We'll feature community libraries in our documentation.

## Need Help?

If you're having trouble integrating the API or need examples for a specific use case:

* Check the [API Reference](https://docs.terraquakeapi.com/api/earthquakes/overview.md) for endpoint details
* Visit our [GitHub Issues](https://github.com/nagcas/TerraQuakeApi/issues) to ask questions
* Join our [Discord community](https://discord.gg/RDBp8KJB) for real-time help


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.