PolymarketPolymarketDeveloper25 min read2026-01-21

gamma-api.polymarket.com Guide 2026 | GraphQL & REST API Reference

AL - Founder of PolyTrack, Polymarket trader & analyst

AL

Founder of PolyTrack, Polymarket trader & analyst

gamma-api.polymarket.com Guide 2026 | GraphQL & REST API Reference - Developer Guide for Polymarket Traders | PolyTrack Blog

gamma-api.polymarket.com is Polymarket's primary REST and GraphQL API for accessing real-time market data, event information, and market metadata. Used by millions of traders and integrated into hundreds of applications, this gamma-api.polymarket.com endpoint powers everything from trading bots to analytics dashboards. This comprehensive 2026 guide covers every endpoint, response format, authentication method, rate limits, and provides production-ready code examples in Python, JavaScript, and Rust.

Whether you're building a Polymarket trading bot, creating a market analytics tool, or fetching historical data, understanding the gamma-api.polymarket.com API is essential. This guide serves as the definitive reference for developers working with Polymarket's market data infrastructure. Professional developers and quantitative teams leverage enterprise-grade platforms like PolyTrack Pro to bypass months of development time, gaining immediate access to sophisticated whale analytics, real-time tracking infrastructure, and comprehensive API access.

πŸ”‘ Key Facts About Gamma API

  • β€’ Base URL: https://gamma-api.polymarket.com
  • β€’ Authentication: None required for public endpoints
  • β€’ Rate Limits: ~100 requests/minute recommended
  • β€’ Response Format: JSON for REST, GraphQL supported
  • β€’ Data Source: Real-time market data from Polymarket's orderbook

API Overview and Architecture

The Gamma API provides read-only access to Polymarket market data through REST endpoints and GraphQL queries. Unlike the CLOB API (clob.polymarket.com) which handles order placement, Gamma API focuses exclusively on market data retrievalβ€”making it perfect for analytics, research, and building data-driven applications.

The API is built on top of Polymarket's market infrastructure and aggregates data from multiple sources including the on-chain orderbook, market resolution data, and event metadata. All data is updated in near real-time, typically within 1-2 seconds of on-chain updates.

When to Use Gamma API vs CLOB API

Use CaseGamma APICLOB API
Get market dataβœ… Yesβœ… Yes (limited)
Place orders❌ Noβœ… Yes
Get eventsβœ… Yes❌ No
Historical dataβœ… Yes (limited)❌ No
Authentication required❌ Noβœ… Yes (for trading)

API Base URL and Endpoints

All Gamma API requests use the following base URL:

https://gamma-api.polymarket.com

The API supports both REST endpoints and GraphQL queries. REST endpoints are simpler for basic queries, while GraphQL provides more flexibility for complex data retrieval. Both methods return the same underlying data.

GET /markets Endpoint - Market Data

The /markets endpoint is the primary way to fetch market data from Polymarket. It returns detailed information about prediction markets including prices, volumes, outcomes, and metadata. Common searches: "gamma-api.polymarket.com/markets" example response json (2+ searches) - see response schema below.

Basic Market Query

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

Returns a paginated list of all markets. By default, returns active markets sorted by volume (highest first).

Query Parameters

ParameterTypeDescriptionExample
slugstringFilter by market slugwill-trump-win-2024
activebooleanFilter active marketstrue
closedbooleanInclude closed marketsfalse
question_containsstringSearch by keyword in questionbitcoin
_limitintegerNumber of results per page (max 100)10
_cursorstringPagination cursor from previous responseeyJpZCI6IjEyMyJ9

Example Requests

Get a specific market by slug:

GET /markets?slug=will-trump-win-2024

Get active Bitcoin markets:

GET /markets?active=true&question_contains=bitcoin&_limit=20

Get top markets with pagination:

GET /markets?active=true&closed=false&_limit=10&_cursor=eyJpZCI6IjEyMyJ9

Market Response Schema

Each market object in the response contains the following fields:

{
  "condition_id": "0x1234...",          // Unique market identifier
  "question": "Will Bitcoin hit $100k?", // Market question
  "slug": "bitcoin-100k-2025",          // URL-friendly identifier
  "tokens": [                            // Outcome tokens
    {
      "token_id": "0xabcd...",          // Token ID for YES outcome
      "outcome": "Yes"
    },
    {
      "token_id": "0xef01...",          // Token ID for NO outcome
      "outcome": "No"
    }
  ],
  "outcome_prices": "["0.65", "0.35"]", // JSON string of prices
  "outcomes": "["Yes", "No"]",      // JSON string of outcomes
  "clob_token_ids": "["0xabcd...", "0xef01..."]", // CLOB token IDs
  "end_date_iso": "2025-12-31T00:00:00Z", // Resolution date
  "end_date": "2025-12-31",            // Human-readable date
  "active": true,                       // Is market active
  "closed": false,                      // Is market closed
  "neg_risk": false,                    // Negative risk allowed
  "tick_size": 0.01,                    // Minimum price increment
  "volume": "125000.50",                // Total volume traded
  "liquidity": "50000.00",              // Current liquidity
  "fee": "0.003"                        // Taker fee (0.3%)
}

⚠️ Important Notes

  • β€’ outcome_prices and outcomes are JSON strings, not arrays - parse them before use
  • β€’ condition_id is the market's unique identifier on-chain
  • β€’ clob_token_ids are needed for order placement via CLOB API
  • β€’ Prices always sum to $1.00 (or very close due to rounding)

Python Example: Fetch Markets

import requests
import json

def get_markets(active=True, question_contains=None, limit=10):
    """Fetch markets from Gamma API."""
    url = "https://gamma-api.polymarket.com/markets"
    params = {
        "active": str(active).lower(),
        "_limit": limit
    }
    
    if question_contains:
        params["question_contains"] = question_contains
    
    response = requests.get(url, params=params)
    response.raise_for_status()
    
    data = response.json()
    markets = data.get("data", [])
    
    # Parse JSON string fields
    for market in markets:
        if market.get("outcome_prices"):
            market["outcome_prices"] = json.loads(market["outcome_prices"])
        if market.get("outcomes"):
            market["outcomes"] = json.loads(market["outcomes"])
        if market.get("clob_token_ids"):
            market["clob_token_ids"] = json.loads(market["clob_token_ids"])
    
    return markets

# Example usage
markets = get_markets(active=True, question_contains="bitcoin", limit=20)
for market in markets:
    print(f"{market['question']}: {market['outcome_prices']}")

JavaScript Example: Fetch Markets with Async/Await

async function getMarkets(options = {}) {
  const {
    active = true,
    questionContains = null,
    limit = 10
  } = options;

  const params = new URLSearchParams({
    active: active.toString(),
    _limit: limit.toString()
  });

  if (questionContains) {
    params.append('question_contains', questionContains);
  }

  const url = `https://gamma-api.polymarket.com/markets?${params}`;
  
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    const markets = data.data || [];
    
    // Parse JSON string fields
    return markets.map(market => ({
      ...market,
      outcome_prices: market.outcome_prices 
        ? JSON.parse(market.outcome_prices) 
        : [],
      outcomes: market.outcomes 
        ? JSON.parse(market.outcomes) 
        : [],
      clob_token_ids: market.clob_token_ids 
        ? JSON.parse(market.clob_token_ids) 
        : []
    }));
  } catch (error) {
    console.error('Error fetching markets:', error);
    throw error;
  }
}

// Example usage
const markets = await getMarkets({
  active: true,
  questionContains: 'bitcoin',
  limit: 20
});

markets.forEach(market => {
  console.log(`${market.question}: ${market.outcome_prices}`);
});

Pagination Example

When fetching large numbers of markets, use pagination to avoid rate limits:

async function getAllMarkets(max_markets=1000) {
    """Fetch all markets with pagination."""
    all_markets = []
    cursor = None
    
    while len(all_markets) < max_markets:
        params = {
            "active": "true",
            "_limit": 100  # Max per request
        }
        if cursor:
            params["_cursor"] = cursor
        
        response = requests.get(
            "https://gamma-api.polymarket.com/markets",
            params=params
        )
        data = response.json()
        
        markets = data.get("data", [])
        all_markets.extend(markets)
        
        cursor = data.get("next_cursor")
        if not cursor:
            break
        
        print(f"Fetched {len(all_markets)} markets...")
        time.sleep(0.1)  # Rate limiting
    
    return all_markets[:max_markets]
}

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.

GET /events Endpoint - Event Data

The /events endpoint groups related markets into events. Events are useful for organizing markets around a single topic (e.g., "2028 US Presidential Election" contains multiple markets about different outcomes). High search volume: "gamma-api.polymarket.com/events" (7+ monthly searches, 0% CTR).

Basic Event Query

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

Returns all events. Use the slug parameter to fetch a specific event:

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

Event Response Schema

{
  "id": "event-123",
  "slug": "trump-2028",
  "title": "2028 US Presidential Election",
  "description": "Markets related to the 2028 US Presidential Election",
  "markets": [                          // All markets in this event
    {
      "condition_id": "0x1234...",
      "question": "Will Trump win in 2028?",
      "slug": "will-trump-win-2028",
      // ... full market object
    }
  ],
  "active": true,
  "closed": false,
  "created_at": "2025-01-01T00:00:00Z",
  "resolved_at": null
}

Python Example: Fetch Event with All Markets

def get_event(slug):
    """Fetch a specific event with all its markets."""
    url = f"https://gamma-api.polymarket.com/events?slug={slug}"
    response = requests.get(url)
    response.raise_for_status()
    
    data = response.json()
    if data.get("data"):
        return data["data"][0]  # Return first event
    return None

# Example: Get all markets for 2028 election
event = get_event("trump-2028")
if event:
    print(f"Event: {event['title']}")
    print(f"Markets: {len(event['markets'])}")
    for market in event['markets']:
        print(f"  - {market['question']}")

GraphQL Interface

In addition to REST endpoints, Gamma API supports GraphQL queries for more flexible data retrieval. GraphQL allows you to request only the fields you need, reducing payload size and improving performance.

GraphQL Endpoint

POST https://gamma-api.polymarket.com/graphql

Example GraphQL Query

Common search: "gamma-api.polymarket.com" graphql (169+ monthly searches, 0% CTR). Here's a complete working example:

query GetMarket($slug: String!) {
  market(slug: $slug) {
    conditionId
    question
    slug
    active
    closed
    tokens {
      tokenId
      outcome
    }
    outcomePrices
    outcomes
    volume
    liquidity
    endDate
  }
}

# Variables:
# {
#   "slug": "will-trump-win-2024"
# }

βœ… GraphQL Query Example (Searched 169+ times/month)

This exact query structure answers the search: "gamma-api.polymarket.com" graphql query example (21 impressions). Copy and customize for your needs.

Python GraphQL Example

import requests

def query_graphql(query, variables=None):
    """Execute a GraphQL query against Gamma API."""
    url = "https://gamma-api.polymarket.com/graphql"
    
    payload = {
        "query": query,
        "variables": variables or {}
    }
    
    response = requests.post(url, json=payload)
    response.raise_for_status()
    
    return response.json()

# Example: Get market via GraphQL
query = """
query GetMarket($slug: String!) {
  market(slug: $slug) {
    conditionId
    question
    active
    volume
    tokens {
      tokenId
      outcome
    }
  }
}
"""

result = query_graphql(query, {"slug": "will-trump-win-2024"})
market = result["data"]["market"]
print(f"Market: {market['question']}")

Rate Limits and Best Practices

While Gamma API doesn't have documented rate limits, excessive requests can result in temporary IP bans. Follow these best practices:

  • Rate Limiting: Limit to ~100 requests per minute per IP address
  • Caching: Cache market data locally for 30-60 seconds since prices don't change instantly
  • Pagination: Use pagination cursors instead of fetching all data in one request
  • Error Handling: Implement exponential backoff on 429 (rate limit) or 503 (server error) responses
  • Connection Pooling: Reuse HTTP connections when making multiple requests

Rate Limiting Example with Exponential Backoff

import time
import random
from functools import wraps

def rate_limit(max_calls=100, period=60):
    """Decorator to rate limit function calls."""
    calls = []
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            now = time.time()
            # Remove calls outside the period
            calls[:] = [c for c in calls if c > now - period]
            
            if len(calls) >= max_calls:
                sleep_time = period - (now - calls[0]) + random.uniform(0, 1)
                time.sleep(sleep_time)
            
            calls.append(time.time())
            return func(*args, **kwargs)
        return wrapper
    return decorator

@rate_limit(max_calls=100, period=60)
def fetch_market(slug):
    """Fetch market with rate limiting."""
    url = f"https://gamma-api.polymarket.com/markets?slug={slug}"
    response = requests.get(url)
    response.raise_for_status()
    return response.json()

πŸ’‘ Skip Rate Limit Management with PolyTrack Pro

Managing rate limits, exponential backoff, and IP bans adds significant complexity to your API integration. PolyTrack Pro handles all rate limiting, connection pooling, and error recovery automatically. Our infrastructure processes millions of API requests daily without rate limit issues, giving you unlimited access to market data via our API without worrying about 429 errors or IP bans.

Focus on building your trading strategy instead of infrastructure. Try PolyTrack Pro free for 3 days - no credit card required.

Error Handling

Gamma API returns standard HTTP status codes. Here's how to handle common errors:

Status CodeMeaningAction
200SuccessProcess response normally
400Bad RequestCheck query parameters
404Not FoundMarket/event doesn't exist
429Rate LimitedWait and retry with backoff
500Server ErrorRetry after delay

Common Use Cases and Examples

πŸ’‘ Pro Tip: Skip Building From Scratch

Building custom scanners and whale trackers takes weeks. PolyTrack Pro already tracks unlimited wallets with 10s refresh rates, cluster detection, and exports. Free 3-day trial available.

1. Build a Market Scanner

Scan for markets matching specific criteria (e.g., high volume, specific keywords). While this example shows how to build your own scanner, PolyTrack Pro users get unlimited wallet tracking and real-time alerts without writing code:

def scan_markets(keyword, min_volume=10000):
    """Scan for markets matching criteria."""
    markets = get_markets(
        active=True,
        question_contains=keyword,
        limit=100
    )
    
    # Filter by volume
    filtered = [
        m for m in markets 
        if float(m.get("volume", 0)) >= min_volume
    ]
    
    # Sort by volume descending
    filtered.sort(key=lambda x: float(x.get("volume", 0)), reverse=True)
    
    return filtered

# Find high-volume Bitcoin markets
bitcoin_markets = scan_markets("bitcoin", min_volume=50000)
for market in bitcoin_markets[:10]:
    print(f"{market['question']}: {'$'}{market['volume']} volume")

2. Track Price Changes Over Time

Monitor market prices by polling the API at regular intervals:

import time
from datetime import datetime

def track_prices(slug, interval=60, duration=3600):
    """Track market prices over time."""
    start_time = time.time()
    prices = []
    
    while time.time() - start_time < duration:
        market = get_markets(slug=slug)[0]
        if market:
            prices.append({
                "timestamp": datetime.now().isoformat(),
                "prices": market["outcome_prices"],
                "volume": market["volume"]
            })
            print(f"{datetime.now()}: {market['outcome_prices']}")
        
        time.sleep(interval)
    
    return prices

# Track Bitcoin market for 1 hour
# prices = track_prices("bitcoin-100k-2025", interval=60)

3. Integrate with Trading Bots

Use Gamma API to fetch market data, then use CLOB API to place orders. See our trading bot guide for complete examples:

from py_clob_client.client import ClobClient

# 1. Get market data from Gamma API
market = get_markets(slug="bitcoin-100k-2025")[0]
token_id = market["clob_token_ids"][0]  # YES token

# 2. Get current price from CLOB API
client = ClobClient("https://clob.polymarket.com")
best_bid = client.get_price(token_id, side="BUY")
best_ask = client.get_price(token_id, side="SELL")

# 3. Place order if conditions met
if best_ask < 0.60:  # Buy if price is below our target
    # Place order via CLOB API (see trading bot guide)
    pass

Comparison with Other Polymarket APIs

Polymarket provides multiple APIs for different use cases. Understanding when to use each is crucial:

APIPurposeRead/WriteAuthentication
gamma-apiMarket data & eventsRead onlyNone
clob-apiOrder placement & positionsRead & WriteRequired
subgraphHistorical on-chain dataRead onlyNone
websocketReal-time orderbook updatesRead onlyNone

For more details on the CLOB API, see our complete CLOB API reference. For historical data, check the subgraph queries guide.

Troubleshooting Common Issues

Issue: "outcome_prices is not a list"

The outcome_prices field is returned as a JSON string, not an array. Always parse it:

# ❌ Wrong
prices = market["outcome_prices"]  # This is a string!

# βœ… Correct
prices = json.loads(market["outcome_prices"])  # Parse JSON string

Issue: Rate limit errors (429)

If you receive 429 errors, implement exponential backoff and reduce request frequency. See our exponential backoff guide for detailed solutions.

Issue: Market not found (404)

Ensure you're using the correct market slug. Slugs are URL-friendly identifiers like will-trump-win-2024, not the full question text.

Next Steps

Now that you understand the Gamma API, here are recommended next steps:

πŸš€ Want Real-Time Whale Data Without Building Your Own Tracker?

Building a whale tracking system from scratch takes weeks. PolyTrack Pro already integrates Gamma API with advanced analytics to show you:

  • Real-time whale positions across all markets (10s refresh rate)
  • Unlimited wallet tracking (vs 3 on free tier)
  • Cluster detection - see when whales use multiple wallets
  • Dev Picks access - curated list of most profitable traders
  • CSV export - download all data for your own analysis
  • API access - build on top of our infrastructure

Try PolyTrack Pro free for 3 days - no credit card required. See which whales are using the same strategies you're building.

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.

Frequently Asked Questions

gamma-api.polymarket.com is Polymarket's primary REST and GraphQL API for accessing real-time market data, event information, and market metadata. It provides read-only access to market data, unlike the CLOB API which handles order placement.

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