Back to Home
GLOOOP
API Docs

Code Examples

Real-world code examples for integrating the Glooop API in JavaScript, Python, and cURL.

JavaScript / TypeScript

Fetch All Deals

// Using fetch API
const API_KEY = process.env.GLOOOP_API_KEY;
const BASE_URL = 'https://api.glooop.fun/api/v1/public/v1';

async function getAllDeals() {
  try {
    const response = await fetch(`${BASE_URL}/deals`, {
      headers: {
        'X-API-Key': API_KEY
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Deals:', data.data.deals);
    return data.data.deals;
  } catch (error) {
    console.error('Error fetching deals:', error);
    throw error;
  }
}

getAllDeals();

Filter Deals by Category

async function getDealsBy Category(category, minDiscount = 0) {
  const params = new URLSearchParams({
    category,
    minDiscount: minDiscount.toString(),
    limit: '20'
  });

  const response = await fetch(
    `${BASE_URL}/deals?${params}`,
    { headers: { 'X-API-Key': API_KEY } }
  );

  const data = await response.json();
  return data.data.deals;
}

// Get all food deals with at least 30% discount
const foodDeals = await getDealsByCategory('FOOD', 30);

Handle Rate Limiting with Retry

async function apiRequestWithRetry(endpoint, maxRetries = 3) {
  let retries = 0;

  while (retries < maxRetries) {
    try {
      const response = await fetch(`${BASE_URL}${endpoint}`, {
        headers: { 'X-API-Key': API_KEY }
      });

      // Check rate limit headers
      const remaining = parseInt(
        response.headers.get('X-RateLimit-Remaining') || '0'
      );
      console.log(`Requests remaining: ${remaining}`);

      if (response.status === 429) {
        // Rate limited - wait and retry
        const resetTime = parseInt(
          response.headers.get('X-RateLimit-Reset') || '0'
        );
        const now = Math.floor(Date.now() / 1000);
        const waitTime = Math.max((resetTime - now) * 1000, 1000);

        console.log(`Rate limited. Waiting ${waitTime}ms...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        retries++;
        continue;
      }

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      if (retries === maxRetries - 1) throw error;
      retries++;
      await new Promise(resolve => setTimeout(resolve, 1000 * retries));
    }
  }
}

// Usage
const deals = await apiRequestWithRetry('/deals');

React Hook for Fetching Deals

import { useState, useEffect } from 'react';

function useGloopDeals(category = null) {
  const [deals, setDeals] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchDeals() {
      try {
        setLoading(true);
        const params = category ? `?category=${category}` : '';
        const response = await fetch(
          `${BASE_URL}/deals${params}`,
          { headers: { 'X-API-Key': process.env.NEXT_PUBLIC_GLOOOP_API_KEY } }
        );

        if (!response.ok) throw new Error('Failed to fetch deals');

        const data = await response.json();
        setDeals(data.data.deals);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    fetchDeals();
  }, [category]);

  return { deals, loading, error };
}

// Usage in component
function DealsPage() {
  const { deals, loading, error } = useGloopDeals('FOOD');

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      {deals.map(deal => (
        <div key={deal.id}>{deal.title}</div>
      ))}
    </div>
  );
}

Python

Fetch All Deals

import requests
import os

API_KEY = os.getenv('GLOOOP_API_KEY')
BASE_URL = 'https://api.glooop.fun/api/v1/public/v1'

def get_all_deals():
    """Fetch all active deals from Glooop API."""
    headers = {'X-API-Key': API_KEY}

    try:
        response = requests.get(
            f'{BASE_URL}/deals',
            headers=headers
        )
        response.raise_for_status()

        data = response.json()
        return data['data']['deals']
    except requests.exceptions.RequestException as e:
        print(f'Error fetching deals: {e}')
        raise

# Usage
deals = get_all_deals()
for deal in deals:
    print(f"{deal['title']} - {deal['discountPercentage']}% off")

Complete API Client Class

import requests
import time
from typing import Optional, Dict, List

class GloopAPIClient:
    """Python client for Glooop Public API."""

    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://api.glooop.fun/api/v1/public/v1'
        self.session = requests.Session()
        self.session.headers.update({'X-API-Key': api_key})

    def _make_request(
        self,
        endpoint: str,
        params: Optional[Dict] = None,
        max_retries: int = 3
    ) -> Dict:
        """Make API request with retry logic."""
        url = f'{self.base_url}{endpoint}'
        retries = 0

        while retries < max_retries:
            try:
                response = self.session.get(url, params=params)

                # Handle rate limiting
                if response.status_code == 429:
                    reset_time = int(response.headers.get('X-RateLimit-Reset', 0))
                    wait_time = max(reset_time - int(time.time()), 1)
                    print(f'Rate limited. Waiting {wait_time}s...')
                    time.sleep(wait_time)
                    retries += 1
                    continue

                response.raise_for_status()
                return response.json()

            except requests.exceptions.RequestException as e:
                if retries == max_retries - 1:
                    raise
                retries += 1
                time.sleep(2 ** retries)  # Exponential backoff

    def get_deals(
        self,
        category: Optional[str] = None,
        min_discount: Optional[int] = None,
        page: int = 1,
        limit: int = 10
    ) -> List[Dict]:
        """Fetch deals with optional filters."""
        params = {'page': page, 'limit': limit}
        if category:
            params['category'] = category
        if min_discount:
            params['minDiscount'] = min_discount

        data = self._make_request('/deals', params)
        return data['data']['deals']

    def get_deal(self, deal_id: str) -> Dict:
        """Get specific deal by ID."""
        data = self._make_request(f'/deals/{deal_id}')
        return data['data']['deal']

    def get_marketplace_listings(self, page: int = 1) -> List[Dict]:
        """Fetch marketplace listings."""
        params = {'page': page, 'limit': 20}
        data = self._make_request('/marketplace/listings', params)
        return data['data']['listings']

    def get_platform_stats(self) -> Dict:
        """Get platform-wide statistics."""
        data = self._make_request('/stats')
        return data['data']['stats']

# Usage
client = GloopAPIClient(os.getenv('GLOOOP_API_KEY'))

# Get all food deals
food_deals = client.get_deals(category='FOOD', min_discount=30)

# Get platform stats
stats = client.get_platform_stats()
print(f"Total deals: {stats['totalDeals']}")
print(f"Total NFTs minted: {stats['totalNFTsMinted']}")

cURL

Common cURL Examples

Get All Deals

curl -X GET "https://api.glooop.fun/api/v1/public/v1/deals" \
  -H "X-API-Key: glp_sk_YOUR_API_KEY_HERE"

Get Deals with Filters

curl -X GET "https://api.glooop.fun/api/v1/public/v1/deals?category=FOOD&minDiscount=30&limit=20" \
  -H "X-API-Key: glp_sk_YOUR_API_KEY_HERE"

Get Specific Deal

curl -X GET "https://api.glooop.fun/api/v1/public/v1/deals/deal_123" \
  -H "X-API-Key: glp_sk_YOUR_API_KEY_HERE"

Get Platform Stats

curl -X GET "https://api.glooop.fun/api/v1/public/v1/stats" \
  -H "X-API-Key: glp_sk_YOUR_API_KEY_HERE"

Get Marketplace Listings

curl -X GET "https://api.glooop.fun/api/v1/public/v1/marketplace/listings?page=1&limit=10" \
  -H "X-API-Key: glp_sk_YOUR_API_KEY_HERE" \
  | jq '.data.listings'