Building with the Hoops API
Welcome to the practical guide for integrating with the Hoops Finance API! This section provides real-world examples and code snippets to help you build powerful DeFi applications quickly.
What You'll Learn
- Analytics Dashboards - Build comprehensive DeFi analytics with TVL, volume, and fee data
- Wallet Tracking - Monitor wallet balances, transactions, and operations on Stellar
- Token Data Management - Fetch and display token metadata for UI components
- Liquidity Monitoring - Track pool health and identify trading opportunities
Supported Languages & Tools
The Hoops Finance API is accessible via any language that can make HTTP requests. Below are examples in multiple languages to help you get started quickly.
All JavaScript and TypeScript examples use the native fetch API, which is built into modern browsers and Node.js 18+. No extra dependencies required.
Basic API Setup
- Python
- JavaScript
- TypeScript
- cURL
- Go
- Rust
- Java
- Shell
import requests
import json
BASE_URL = "https://api.hoops.finance"
def make_request(endpoint):
"""Make a GET request to the Hoops Finance API"""
url = f"{BASE_URL}/{endpoint}"
response = requests.get(url)
response.raise_for_status()
return response.json()
const BASE_URL = "https://api.hoops.finance";
async function makeRequest(endpoint) {
const url = `${BASE_URL}/${endpoint}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
const BASE_URL = "https://api.hoops.finance";
interface ApiResponse<T> {
data: T;
status: number;
}
async function makeRequest<T>(endpoint: string): Promise<T> {
const url = `${BASE_URL}/${endpoint}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
BASE_URL="https://api.hoops.finance"
make_request() {
local endpoint=$1
curl -s "${BASE_URL}/${endpoint}" | jq .
}
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const BASE_URL = "https://api.hoops.finance"
func makeRequest(endpoint string) ([]byte, error) {
url := fmt.Sprintf("%s/%s", BASE_URL, endpoint)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
use reqwest;
use serde_json::Value;
const BASE_URL: &str = "https://api.hoops.finance";
async fn make_request(endpoint: &str) -> Result<Value, Box<dyn std::error::Error>> {
let url = format!("{}/{}", BASE_URL, endpoint);
let response = reqwest::get(&url).await?;
let data: Value = response.json().await?;
Ok(data)
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class HoopsApiClient {
private static final String BASE_URL = "https://api.hoops.finance";
private final HttpClient client = HttpClient.newHttpClient();
public String makeRequest(String endpoint) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/" + endpoint))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
#!/bin/bash
BASE_URL="https://api.hoops.finance"
make_request() {
local endpoint=$1
curl -s "${BASE_URL}/${endpoint}" | jq .
}
# Usage: make_request "protocols"
Getting Started
The Hoops Finance Public AMM API doesn't require API keys for most endpoints, making it perfect for quick prototyping and development.
Recommended Tools
Python:
requests
- HTTP library for API callspandas
- Data manipulation and analysisplotly
ormatplotlib
- Data visualization
JavaScript:
- Native
fetch
API - Built-in HTTP client (no dependencies) chart.js
ord3.js
- Charting and visualization
API Base URLs
- Production:
https://api.hoops.finance
- Local Development:
http://localhost:9999
Rate Limits
- 120 requests per minute
- 30 requests burst limit
- Monitor with
X-RateLimit-*
headers
Stellar Classic Endpoints
Some endpoints work with Stellar Classic blockchain data. These are clearly marked throughout the documentation.
Endpoints that support Stellar Classic include:
- Account information and balances
- Transaction history
- Asset details
- Payment tracking
Quick Example
Here's a simple example to get platform metrics in multiple languages:
- Python
- JavaScript
- TypeScript
- cURL
- Go
- Rust
- Java
- Shell
import requests
def get_platform_metrics():
"""Fetch basic platform metrics"""
response = requests.get("https://api.hoops.finance/getmetrics?period=24h")
return response.json()
# Usage
metrics = get_platform_metrics()
print(f"Total TVL: ${metrics['tvl']:,.2f}")
print(f"24h Volume: ${metrics['volume24h']:,.2f}")
async function getPlatformMetrics() {
const response = await fetch('https://api.hoops.finance/getmetrics?period=24h');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// Usage
getPlatformMetrics().then(metrics => {
console.log(`Total TVL: $${metrics.tvl.toLocaleString()}`);
console.log(`24h Volume: $${metrics.volume24h.toLocaleString()}`);
});
interface PlatformMetrics {
tvl: number;
volume24h: number;
fees24h: number;
activePairs: number;
}
async function getPlatformMetrics(): Promise<PlatformMetrics> {
const response = await fetch('https://api.hoops.finance/getmetrics?period=24h');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// Usage
getPlatformMetrics().then(metrics => {
console.log(`Total TVL: $${metrics.tvl.toLocaleString()}`);
console.log(`24h Volume: $${metrics.volume24h.toLocaleString()}`);
});
# Get platform metrics
curl -s "https://api.hoops.finance/getmetrics?period=24h" | jq '.'
# Extract specific values
TVL=$(curl -s "https://api.hoops.finance/getmetrics?period=24h" | jq -r '.tvl')
VOLUME=$(curl -s "https://api.hoops.finance/getmetrics?period=24h" | jq -r '.volume24h')
echo "Total TVL: \$${TVL}"
echo "24h Volume: \$${VOLUME}"
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type PlatformMetrics struct {
TVL float64 `json:"tvl"`
Volume24h float64 `json:"volume24h"`
Fees24h float64 `json:"fees24h"`
ActivePairs int `json:"activePairs"`
}
func getPlatformMetrics() (*PlatformMetrics, error) {
resp, err := http.Get("https://api.hoops.finance/getmetrics?period=24h")
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var metrics PlatformMetrics
err = json.Unmarshal(body, &metrics)
return &metrics, err
}
func main() {
metrics, err := getPlatformMetrics()
if err != nil {
panic(err)
}
fmt.Printf("Total TVL: $%.2f\n", metrics.TVL)
fmt.Printf("24h Volume: $%.2f\n", metrics.Volume24h)
}
use reqwest;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct PlatformMetrics {
tvl: f64,
volume24h: f64,
fees24h: f64,
active_pairs: i32,
}
async fn get_platform_metrics() -> Result<PlatformMetrics, Box<dyn std::error::Error>> {
let response = reqwest::get("https://api.hoops.finance/getmetrics?period=24h").await?;
let metrics: PlatformMetrics = response.json().await?;
Ok(metrics)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let metrics = get_platform_metrics().await?;
println!("Total TVL: ${:.2}", metrics.tvl);
println!("24h Volume: ${:.2}", metrics.volume24h);
Ok(())
}
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class PlatformMetrics {
private double tvl;
private double volume24h;
private double fees24h;
private int activePairs;
// Getters and setters
public double getTvl() { return tvl; }
public void setTvl(double tvl) { this.tvl = tvl; }
public double getVolume24h() { return volume24h; }
public void setVolume24h(double volume24h) { this.volume24h = volume24h; }
// ... other getters/setters
}
public class HoopsApiClient {
private static final String BASE_URL = "https://api.hoops.finance";
private final HttpClient client = HttpClient.newHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
public PlatformMetrics getPlatformMetrics() throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + "/getmetrics?period=24h"))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return mapper.readValue(response.body(), PlatformMetrics.class);
}
public static void main(String[] args) throws Exception {
HoopsApiClient client = new HoopsApiClient();
PlatformMetrics metrics = client.getPlatformMetrics();
System.out.printf("Total TVL: $%.2f%n", metrics.getTvl());
System.out.printf("24h Volume: $%.2f%n", metrics.getVolume24h());
}
}
#!/bin/bash
BASE_URL="https://api.hoops.finance"
get_platform_metrics() {
curl -s "${BASE_URL}/getmetrics?period=24h" | jq '.'
}
# Usage
metrics=$(get_platform_metrics)
tvl=$(echo "$metrics" | jq -r '.tvl')
volume=$(echo "$metrics" | jq -r '.volume24h')
echo "Total TVL: \$${tvl}"
echo "24h Volume: \$${volume}"
What's Next?
- 📊 Analytics Dashboard - Build comprehensive DeFi analytics
- 👛 Wallet Tracking - Monitor wallet activity and balances
- 💠 Token Data - Manage token metadata and information
- 🌊 Liquidity Monitoring - Track pool health and opportunities
API Reference
For complete endpoint documentation, visit the API Reference section.
Support
Need help? Contact us at [email protected] or check out our interactive API testing tools.