Official SDKs
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 .
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)
// 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
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
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)
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
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
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
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
Implement exponential backoff and respect rate limits to avoid throttling. 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' );
}
Always handle errors gracefully and check the success field in responses. 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 } " )
Cache responses when appropriate to reduce API calls and improve performance. 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()
We welcome community-built SDKs and client libraries!
Contribute an SDK Build and submit an official SDK for your favorite language
Join Discord Discuss SDK development with the community
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: