How to Use Polymarket API: Complete Developer Guide (2026)
Build prediction market apps with Polymarket's REST and WebSocket APIs
Hypereal로 구축 시작하기
단일 API를 통해 Kling, Flux, Sora, Veo 등에 액세스하세요. 무료 크레딧으로 시작하고 수백만으로 확장하세요.
신용카드 불필요 • 10만 명 이상의 개발자 • 엔터프라이즈 지원
How to Use Polymarket API: Complete Developer Guide (2026)
Polymarket is the largest prediction market platform, allowing users to trade on the outcomes of real-world events. Whether you want to build a dashboard, automate trading strategies, or pull market data into your application, the Polymarket API gives you programmatic access to everything on the platform.
This guide walks through the full Polymarket API setup, from authentication to placing your first trade, with working code examples in Python and JavaScript.
Polymarket API Overview
Polymarket exposes two main APIs:
| API | Purpose | Authentication | Rate Limit |
|---|---|---|---|
| CLOB API | Trading, order placement, market data | API key + secret | 100 req/min |
| Gamma API | Public market data, events, metadata | None (public) | 300 req/min |
The CLOB (Central Limit Order Book) API is what you need for trading. The Gamma API is a read-only REST API for fetching market information, event details, and historical data without authentication.
Step 1: Get Your Polymarket API Key
To use the CLOB API, you need an API key tied to your Polymarket wallet.
- Go to polymarket.com and connect your wallet or create an account.
- Navigate to your account settings and find the API section.
- Generate a new API key and secret. Store these securely -- you will not see the secret again.
For the Gamma API, no authentication is required. You can start making requests immediately.
Step 2: Fetch Market Data with the Gamma API
The Gamma API is the easiest way to get started. It returns structured data about all active markets.
List All Active Markets
import requests
# Fetch active markets from Polymarket Gamma API
response = requests.get(
"https://gamma-api.polymarket.com/markets",
params={
"active": "true",
"limit": 10,
"order": "volume24hr",
"ascending": "false"
}
)
markets = response.json()
for market in markets:
print(f"Question: {market['question']}")
print(f"Volume (24h): ${market.get('volume24hr', 0):,.2f}")
print(f"Liquidity: ${market.get('liquidity', 0):,.2f}")
print("---")
// Node.js / fetch example
const response = await fetch(
"https://gamma-api.polymarket.com/markets?" +
new URLSearchParams({
active: "true",
limit: "10",
order: "volume24hr",
ascending: "false"
})
);
const markets = await response.json();
markets.forEach(market => {
console.log(`Question: ${market.question}`);
console.log(`Volume (24h): $${Number(market.volume24hr || 0).toLocaleString()}`);
console.log(`Liquidity: $${Number(market.liquidity || 0).toLocaleString()}`);
console.log("---");
});
Get a Specific Market by ID
import requests
market_id = "0x1234..." # Replace with actual condition ID
response = requests.get(
f"https://gamma-api.polymarket.com/markets/{market_id}"
)
market = response.json()
print(f"Question: {market['question']}")
print(f"Description: {market['description']}")
print(f"End Date: {market['endDate']}")
Search Markets by Keyword
import requests
response = requests.get(
"https://gamma-api.polymarket.com/markets",
params={
"tag": "politics",
"active": "true",
"limit": 5
}
)
markets = response.json()
for m in markets:
print(f"{m['question']} — Volume: ${m.get('volume24hr', 0):,.0f}")
Step 3: Connect to the CLOB API for Trading
The CLOB API lets you place and manage orders. It requires cryptographic authentication using your API credentials.
Install the Python Client
pip install py-clob-client
Initialize the Client
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import ApiCreds
# Your credentials
host = "https://clob.polymarket.com"
chain_id = 137 # Polygon mainnet
private_key = "0xYOUR_PRIVATE_KEY"
# Initialize the client
client = ClobClient(
host,
key=private_key,
chain_id=chain_id
)
# Derive API credentials
api_creds = client.create_or_derive_api_creds()
client.set_api_creds(api_creds)
print("Connected to Polymarket CLOB API")
Fetch Order Book Data
# Get the order book for a specific market
token_id = "71321045..." # The token ID for a specific outcome
order_book = client.get_order_book(token_id)
print("Bids:")
for bid in order_book.bids[:5]:
print(f" Price: {bid.price} | Size: {bid.size}")
print("Asks:")
for ask in order_book.asks[:5]:
print(f" Price: {ask.price} | Size: {ask.size}")
Place a Limit Order
from py_clob_client.order_builder.constants import BUY
# Create and sign a limit order
order_args = {
"token_id": "71321045...",
"price": 0.55, # Price in USDC (0.55 = 55 cents = 55% probability)
"size": 100, # Number of shares
"side": BUY,
"fee_rate_bps": 0, # Fee in basis points
}
signed_order = client.create_and_post_order(order_args)
print(f"Order placed: {signed_order}")
Cancel an Order
# Cancel a specific order
order_id = "0xABC123..."
result = client.cancel(order_id)
print(f"Order cancelled: {result}")
# Cancel all open orders
result = client.cancel_all()
print(f"All orders cancelled: {result}")
Step 4: Stream Real-Time Data with WebSockets
Polymarket offers WebSocket connections for real-time price updates and order book changes.
import asyncio
import websockets
import json
async def stream_market_data():
uri = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
async with websockets.connect(uri) as ws:
# Subscribe to a market
subscribe_msg = {
"type": "subscribe",
"market": "71321045...", # Token ID
"channel": "price"
}
await ws.send(json.dumps(subscribe_msg))
print("Subscribed to price updates")
async for message in ws:
data = json.loads(message)
print(f"Price update: {data}")
asyncio.run(stream_market_data())
Step 5: Build a Simple Market Dashboard
Here is a practical example that pulls the top markets and displays them in a formatted table.
import requests
from tabulate import tabulate
def get_top_markets(limit=10):
response = requests.get(
"https://gamma-api.polymarket.com/markets",
params={
"active": "true",
"limit": limit,
"order": "volume24hr",
"ascending": "false"
}
)
return response.json()
def format_market_table(markets):
rows = []
for m in markets:
rows.append([
m["question"][:60],
f"${float(m.get('volume24hr', 0)):,.0f}",
f"${float(m.get('liquidity', 0)):,.0f}",
m.get("endDate", "N/A")[:10]
])
headers = ["Market", "24h Volume", "Liquidity", "End Date"]
return tabulate(rows, headers=headers, tablefmt="grid")
markets = get_top_markets()
print(format_market_table(markets))
Polymarket API Rate Limits and Best Practices
| Endpoint | Rate Limit | Recommended Interval |
|---|---|---|
| Gamma API (public) | 300 req/min | 200ms between requests |
| CLOB REST API | 100 req/min | 600ms between requests |
| WebSocket | No hard limit | Use heartbeat pings every 30s |
| Order placement | 10 orders/sec | Batch when possible |
Best practices
- Cache market data. Market metadata does not change frequently. Cache it locally and refresh every 5-10 minutes.
- Use WebSockets for real-time data. Polling the REST API wastes rate limits. Use WebSocket subscriptions for live price feeds.
- Handle 429 errors gracefully. Implement exponential backoff when you hit rate limits.
- Store API keys in environment variables. Never hardcode private keys or API secrets in your code.
import os
# Load from environment variables
api_key = os.environ.get("POLYMARKET_API_KEY")
api_secret = os.environ.get("POLYMARKET_API_SECRET")
private_key = os.environ.get("POLYMARKET_PRIVATE_KEY")
Common API Response Codes
| Code | Meaning | Action |
|---|---|---|
| 200 | Success | Process response |
| 400 | Bad request | Check parameters |
| 401 | Unauthorized | Verify API credentials |
| 404 | Not found | Check market/order ID |
| 429 | Rate limited | Back off and retry |
| 500 | Server error | Retry after delay |
Frequently Asked Questions
Is the Polymarket API free? Yes. The Gamma API is completely free with no authentication required. The CLOB API is free to use but requires a funded Polymarket account to place trades.
Which blockchain does Polymarket use? Polymarket operates on Polygon (chain ID 137). You need USDC on Polygon to trade.
Can I use the API for automated trading bots? Yes. The CLOB API is designed for programmatic trading. Many users run automated strategies. Be aware of the terms of service regarding market manipulation.
Is there a sandbox or testnet? Polymarket has occasionally offered testnet environments for developers. Check their Discord and documentation for current availability.
What programming languages are supported?
The official client library is in Python (py-clob-client). The REST and WebSocket APIs work with any language that supports HTTP requests.
Wrapping Up
The Polymarket API is one of the most accessible prediction market APIs available. The public Gamma API requires zero setup for reading market data, and the CLOB API gives you full trading capabilities with Python client support.
If you are building AI-powered applications that incorporate prediction market data or any kind of media generation, try Hypereal AI free -- 35 credits, no credit card required. It provides simple APIs for image, video, and avatar generation that pair well with data-driven applications.
