PolymarketPolymarketDeveloper18 min read2026-01-21

gamma-api.polymarket.com/events: Complete Events API Guide

AL - Founder of PolyTrack, Polymarket trader & analyst

AL

Founder of PolyTrack, Polymarket trader & analyst

gamma-api.polymarket.com/events: Complete Events API Guide - Developer Guide for Polymarket Traders | PolyTrack Blog

Complete guide to gamma-api.polymarket.com/events endpoint. The Events API allows you to fetch event data, group related markets together, and retrieve event-specific information from Polymarket. Events are collections of related markets—for example, all markets for a specific election or sports event are grouped under a single event. This comprehensive 2026 guide covers endpoint usage, query parameters, response structure, and provides production-ready code examples in Python, JavaScript, and Rust.

The Events API is essential for building event-specific dashboards, grouping related markets, and understanding the context behind individual markets. Whether you're building analytics tools, trading bots, or data aggregators, understanding how to fetch and parse event data is crucial. High search volume: "gamma-api.polymarket.com/events" - developers frequently search for this endpoint reference. Professional developers leverage analytics platforms like PolyTrack Pro to access pre-built event tracking infrastructure and skip months of API integration work.

🔑 Key Facts About Events API

  • Endpoint: https://gamma-api.polymarket.com/events
  • Authentication: None required (public endpoint)
  • Method: GET requests only
  • Response Format: JSON array of event objects
  • Rate Limits: ~100 requests/minute recommended
  • Use Case: Group related markets, fetch event metadata, build event dashboards

GET /events Endpoint - Overview

The /events endpoint returns a list of events, each containing multiple related markets. Events serve as containers for grouping markets—for example, all "Trump 2028" markets might be grouped under a single event with slug trump-2028.

Basic Request

GET https://gamma-api.polymarket.com/events

Returns all events (paginated). Use query parameters to filter results.

Query by Event Slug

Fetch a specific event by slug:

GET https://gamma-api.polymarket.com/events?slug=trump-2028

Returns an array containing the matching event (empty array if not found).

Query Parameters

ParameterTypeDescription
slugstringExact event slug match
slug_containsstringPartial slug match (e.g., "btc-updown-15m")
activebooleanFilter by active status (true/false)
closedbooleanFilter by closed status (true/false)
_limitnumberLimit number of results (default varies)

Response Structure

The endpoint returns a JSON array of event objects. Each event object contains:

[
  {
    "id": "0x123...",
    "slug": "trump-2028",
    "title": "2028 US Presidential Election",
    "description": "Who will win the 2028 US Presidential Election?",
    "markets": [
      {
        "conditionId": "0x456...",
        "question": "Will Donald Trump win the 2028 election?",
        "outcomePrices": "[\"0.45\", \"0.55\"]",
        "outcomes": "[\"Yes\", \"No\"]",
        "active": true,
        "closed": false,
        // ... more market fields
      }
    ],
    "active": true,
    "closed": false
  }
]

Event Object Fields

  • id: Unique event identifier (hex string)
  • slug: URL-friendly identifier (e.g., "trump-2028")
  • title: Human-readable event title
  • description: Event description (may be null)
  • markets: Array of market objects belonging to this event
  • active: Boolean indicating if event is active
  • closed: Boolean indicating if event is closed/resolved

Market Object Fields (Nested)

Each event contains a markets array. Market objects include:

  • conditionId: Unique market condition ID
  • question: Market question text
  • outcomePrices: JSON string array of prices (must parse with JSON.parse)
  • outcomes: JSON string array of outcome names (must parse with JSON.parse)
  • tokens: Array of token objects with token_id and outcome
  • clobTokenIds: JSON string array of CLOB token IDs
  • active: Boolean indicating if market is active
  • closed: Boolean indicating if market is closed
  • endDateIso: ISO timestamp of market end date

⚠️ Important: Parse JSON Strings

Fields like outcomePrices, outcomes, and clobTokenIds are returned as JSON strings, not arrays. You must parse them:

// JavaScript/TypeScript
const prices = JSON.parse(event.markets[0].outcomePrices);
// Result: ["0.45", "0.55"]

// Python
import json
prices = json.loads(event['markets'][0]['outcomePrices'])
# Result: ["0.45", "0.55"]

See What Whales Are Trading Right Now

Get instant alerts when top traders make moves. Track P&L, win rates, and copy winning strategies.

Track Whales Free

Free forever. No credit card required.

Python Examples

Fetch Event by Slug

import requests
import json

def fetch_event_by_slug(slug: str):
    """Fetch a specific event by slug."""
    url = f"https://gamma-api.polymarket.com/events?slug={slug}"
    response = requests.get(url)
    response.raise_for_status()
    
    events = response.json()
    if not events:
        return None
    
    event = events[0]
    # Parse nested JSON strings
    for market in event['markets']:
        if market.get('outcomePrices'):
            market['outcomePrices'] = json.loads(market['outcomePrices'])
        if market.get('outcomes'):
            market['outcomes'] = json.loads(market['outcomes'])
    
    return event

# Usage
event = fetch_event_by_slug("trump-2028")
if event:
    print(f"Event: {event['title']}")
    print(f"Markets: {len(event['markets'])}")
    for market in event['markets']:
        print(f"  - {market['question']}")

Search Active Events with Filtering

def search_active_events(slug_contains: str = None, limit: int = 10):
    """Search for active, non-closed events."""
    url = "https://gamma-api.polymarket.com/events"
    params = {
        "active": "true",
        "closed": "false",
        "_limit": limit
    }
    
    if slug_contains:
        params["slug_contains"] = slug_contains
    
    response = requests.get(url, params=params)
    response.raise_for_status()
    return response.json()

# Usage: Find active BTC 15-minute markets
events = search_active_events(slug_contains="btc-updown-15m", limit=5)
for event in events:
    print(f"{event['slug']}: {len(event['markets'])} markets")

JavaScript/TypeScript Examples

Fetch Event with Error Handling

async function fetchEventBySlug(slug: string) {
  try {
    const url = `https://gamma-api.polymarket.com/events?slug=${slug}`;
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const events = await response.json();
    if (events.length === 0) {
      return null;
    }
    
    const event = events[0];
    // Parse nested JSON strings
    event.markets = event.markets.map(market => ({
      ...market,
      outcomePrices: market.outcomePrices 
        ? JSON.parse(market.outcomePrices) 
        : null,
      outcomes: market.outcomes 
        ? JSON.parse(market.outcomes) 
        : null,
    }));
    
    return event;
  } catch (error) {
    console.error('Failed to fetch event:', error);
    throw error;
  }
}

// Usage
const event = await fetchEventBySlug('trump-2028');
if (event) {
  console.log(`Event: ${event.title}`);
  console.log(`Markets: ${event.markets.length}`);
}

React Hook Example

import { useState, useEffect } from 'react';

function usePolymarketEvent(slug: string) {
  const [event, setEvent] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function loadEvent() {
      try {
        setLoading(true);
        const url = `https://gamma-api.polymarket.com/events?slug=${slug}`;
        const response = await fetch(url);
        const events = await response.json();
        
        if (events.length > 0) {
          const parsedEvent = {
            ...events[0],
            markets: events[0].markets.map(m => ({
              ...m,
              outcomePrices: JSON.parse(m.outcomePrices || '[]'),
              outcomes: JSON.parse(m.outcomes || '[]'),
            }))
          };
          setEvent(parsedEvent);
        } else {
          setEvent(null);
        }
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    loadEvent();
  }, [slug]);

  return { event, loading, error };
}

// Usage in component
function EventDashboard({ slug }: { slug: string }) {
  const { event, loading, error } = usePolymarketEvent(slug);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  if (!event) return <div>Event not found</div>;

  return (
    <div>
      <h1>{event.title}</h1>
      <p>Markets: {event.markets.length}</p>
    </div>
  );
}

Rust Examples

Here's a real-world Rust implementation used in production trading bots:

use serde::{Deserialize, Serialize};
use reqwest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Event {
    pub id: String,
    pub slug: String,
    pub title: String,
    pub markets: Vec<Market>,
    pub active: bool,
    pub closed: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Market {
    pub condition_id: String,
    pub question: String,
    #[serde(default)]
    pub tokens: Vec<Token>,
    pub outcome_prices: Option<String>, // JSON string
    pub outcomes: Option<String>,       // JSON string
    pub active: bool,
    pub closed: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Token {
    pub token_id: String,
    pub outcome: String,
}

pub async fn fetch_event_by_slug(
    client: &reqwest::Client,
    gamma_url: &str,
    slug: &str
) -> Result<Option<Event>, Box<dyn std::error::Error>> {
    let url = format!("{}/events?slug={}", gamma_url, slug);
    let response = client.get(&url).send().await?;
    let events: Vec<Event> = response.json().await?;

    Ok(events.into_iter().next())
}

// Usage with slug_contains for searching
pub async fn search_active_events(
    client: &reqwest::Client,
    gamma_url: &str,
    slug_contains: &str
) -> Result<Vec<Event>, Box<dyn std::error::Error>> {
    let url = format!(
        "{}/events?slug_contains={}&active=true&closed=false&_limit=5",
        gamma_url, slug_contains
    );
    let response = client.get(&url).send().await?;
    let events: Vec<Event> = response.json().await?;
    Ok(events)
}

Common Use Cases

1. Build Event-Specific Dashboards

Group all markets for a specific event into a single dashboard:

  • • Fetch event by slug (e.g., "trump-2028")
  • • Display all markets in the event
  • • Show aggregate statistics (total volume, number of markets)
  • • Filter markets by active/closed status

2. Track Event-Level Metadata

Monitor event status and related information:

  • • Check if event is active or closed
  • • Get event title and description for display
  • • Track when events become active/closed

3. Search for Related Markets

Find all markets related to a topic using slug_contains:

  • • Search for "btc-updown-15m" to find all BTC 15-minute markets
  • • Search for "trump" to find all Trump-related events
  • • Filter by active/closed status to find only active markets

Error Handling and Rate Limiting

Rate Limits

  • Recommended: ~100 requests per minute
  • Best Practice: Implement exponential backoff for retries
  • 429 Status: Too many requests - wait and retry

Error Handling Example

import time
import requests

def fetch_event_with_retry(slug: str, max_retries: int = 3):
    """Fetch event with exponential backoff retry."""
    for attempt in range(max_retries):
        try:
            url = f"https://gamma-api.polymarket.com/events?slug={slug}"
            response = requests.get(url, timeout=10)
            
            if response.status_code == 429:
                wait_time = 2 ** attempt
                print(f"Rate limited, waiting {wait_time}s...")
                time.sleep(wait_time)
                continue
            
            response.raise_for_status()
            events = response.json()
            return events[0] if events else None
            
        except requests.RequestException as e:
            if attempt == max_retries - 1:
                raise
            wait_time = 2 ** attempt
            time.sleep(wait_time)
    
    return None

Best Practices

  • Parse JSON Strings: Always parse outcomePrices, outcomes, and clobTokenIds as JSON
  • Handle Empty Results: Events endpoint returns empty array if no matches - check array length
  • Use Filtering: Use query parameters to filter results server-side (more efficient)
  • Cache Responses: Event data doesn't change frequently - cache when possible
  • Respect Rate Limits: Implement backoff and retry logic for 429 responses
  • Error Handling: Always handle network errors and timeouts gracefully

Conclusion

The /events endpoint is essential for building event-focused applications, grouping related markets, and creating event-specific dashboards. Always remember to parse JSON strings for nested arrays, handle empty results, and implement proper error handling with rate limiting.

For production applications requiring event tracking and market analytics, consider using enterprise platforms like PolyTrack Pro to access pre-built event tracking infrastructure and skip months of API integration work.

Related Resources

Frequently Asked Questions

The /events endpoint returns a list of events, each containing multiple related markets. Events group related markets together - for example, all "Trump 2028" markets might be grouped under a single event. Use this endpoint to fetch event metadata, group markets, and build event-specific dashboards.

12,400+ TRADERS

Stop Guessing. Start Following Smart Money.

Get instant alerts when whales make $10K+ trades. Track P&L, win rates, and copy winning strategies.

Track Whales FreeNo credit card required