# The Graph subgraph API: keys, fees and GraphQL in Python

URL: https://fincodelabs.com/en/blog/the-graph-subgraph-api · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Exchange APIs · Published: 2026-11-27 · Updated: 2026-11-27

The Graph subgraph API read 27 Nov 2026: gateway URL, API keys, 100,000 free queries then $2 per 100,000, id_gt pagination, block pinning and tested Python.

**Short answer:** **The Graph's subgraph API** is a GraphQL endpoint per subgraph: you POST queries to `https://gateway.thegraph.com/api/subgraphs/id/<SUBGRAPH_ID>` with an API key from Subgraph Studio. As The Graph's pricing pages read on 27 November 2026 state, the first 100,000 queries a month are free and further queries cost $2 per 100,000.

This guide uses The Graph's documentation (querying, API keys, billing, the GraphQL API reference), its pricing pages, Uniswap's subgraph page and the Uniswap v3 subgraph schema on GitHub, all read on 27 November 2026, plus live calls to the gateway that day without a key. Everything that needs a key was tested up to the authentication error or against simulated responses, and each place is marked. Pools and tokens named below are examples of data, not of anything to trade.

The Graph publishes an `llms.txt` index that points AI agents to an "agent orientation file" and agent "skills" pages. That material is addressed to automated readers; it was read as data and not followed as instructions.

## The Graph API key and gateway URL

Every query to a published subgraph needs an API key created in Subgraph Studio, passed either in the URL path or as a bearer token.

The Managing API Keys page read on 27 November 2026 gives both forms:

- In the URL: `https://gateway.thegraph.com/api/<API_KEY>/subgraphs/id/<SUBGRAPH_ID>`, which the page calls the optimal method.
- In a header: `Authorization: Bearer <API_KEY>` against `https://gateway.thegraph.com/api/subgraphs/id/<SUBGRAPH_ID>`, described as "added security".

The header form keeps the key out of proxy logs and browser history, which is why the code below uses it. Each key can have a monthly spending limit in USD, a list of allowed domains and a list of allowed subgraphs; regenerating a key invalidates the old one immediately. The page says keys "enforce rate limits" but publishes no number, so treat the limit as unknown. A separate Studio endpoint, `https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>`, exists for testing your own deployment and is documented as rate-limited and not for production. The querying guide adds that a GET to a gateway URL can return 405 and that you should use POST.

## The Graph query fees: free plan and Growth plan

Subgraph queries are billed per query: 100,000 free a month, then $2 per 100,000 on the Growth plan, payable by card or in GRT.

**Subgraph query pricing, The Graph pricing pages read 27 November 2026**

| Plan | Price | Included | Payment |
| --- | --- | --- | --- |
| Free | $0 | 100,000 queries a month | None |
| Growth | $2 per 100,000 queries above the free amount | Usage-based, invoiced monthly | Credit card, or GRT held on Arbitrum One |

The machine-readable pricing file was last updated on 28 May 2026 and gives the worked example that 300,000 queries in a month cost $4. Substreams, a separate streaming product, is priced per provider on The Graph Market and is not covered here. The billing page says GRT for query fees must sit in Studio's billing contract on Arbitrum One, and deposits from Ethereum mainnet are bridged in 15 to 20 minutes.

> **Hypothetical example.** A dashboard runs 4 queries every minute, around the clock: 4 x 60 x 24 x 30 = 172,800 queries in a 30-day month. The first 100,000 are free and the other 72,800 cost 72,800 / 100,000 x $2 = $1.46. A backfill that pages through 2 million entities at 1,000 per query adds 2,000 queries, or $0.04. Query count, not data volume, drives the bill.

## Subgraph IDs: how to find the Uniswap subgraph

A subgraph ID identifies one published subgraph on Graph Explorer, and protocol teams usually publish their own IDs.

Uniswap's subgraph page read on 27 November 2026 lists these gateway IDs for Ethereum mainnet:

**Uniswap subgraph IDs on Ethereum mainnet, read 27 November 2026**

| Version | Subgraph ID |
| --- | --- |
| v4 | `DiYPVdygkfjDWhbxGSqAQxwBKmfKnkWQojqeM2rkLb3G` |
| v3 | `5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV` |
| v2 | `A3Np3RQbaBA6oKJgiwDJeo5T3zrYfGHPWFYayMwtNDum` |

Take IDs from the protocol's own documentation or Graph Explorer, not from a blog post, because a lookalike subgraph can index a different contract. The `_meta` field returns the `deployment` being served (the IPFS hash of the manifest), the latest indexed `block` and `hasIndexingErrors`, so log it with every batch. The Uniswap v3 schema in the GitHub repository defines `Pool` with `id` (Bytes), `feeTier`, `token0`, `token1`, `volumeUSD` and `totalValueLockedUSD`, but the deployed version can lag the repository, so check fields on the subgraph page in Graph Explorer. For Uniswap's other data routes, see the [Uniswap API guide](https://fincodelabs.com/en/blog/uniswap-api).

## Why The Graph returns auth errors with HTTP 200

The gateway reports authentication failures inside a GraphQL `errors` array with status 200, so code that only checks the HTTP status will treat a failed query as a success.

**Live gateway responses, 27 November 2026**

| Request | HTTP status | Body |
| --- | ---: | --- |
| POST, no key | 200 | `auth error: missing authorization header` |
| POST, `Authorization: Bearer` with an empty key | 200 | `auth error: invalid authorization header` |
| POST, 32-character made-up key in URL or header | 200 | `auth error: API key not found` |
| POST, key `abc` in URL | 200 | `auth error: malformed API key` |
| POST, invalid JSON body, no key | 200 | `auth error: missing authorization header` |
| GET, no key | 200 | `auth error: missing authorization header` |

Two lessons follow. First, always check `errors` before reading `data`; GraphQL can also return partial data together with errors. Second, authentication is checked before the body is parsed, so a broken query and a missing key look the same until the key is valid. The GET responses carried an `allow: POST` header; the documented 405 for GET could not be reproduced without a key.

## Subgraph pagination with first and id_gt

Page through large collections with `first` up to 1,000, ordered by `id`, filtering each page with `id_gt` set to the last id you received.

The GraphQL API reference read on 27 November 2026 says collection queries return at most 100 entities when `first` is omitted, that the maximum for `first` is 1,000 (the Graph Node default, set by `GRAPH_GRAPHQL_MAX_FIRST`) and that requesting more returns an error, that the default sort is by ID in ascending alphanumeric order, "not by creation time", and that `skip` generally performs poorly. Its cursor example uses `where: { id_gt: $lastID }`.

Paging across many requests has a second problem: new blocks arrive between pages, so page 3 can reflect a later chain state than page 1. The reference documents time-travel queries with `block: { number: N }` or `block: { hash: "0x..." }`. Reading `_meta { block { number } }` once and passing that number to every page gives one consistent snapshot. The reference warns that for blocks that are not yet final, a chain reorganization can still affect results, so pinning a block a few confirmations behind the head is safer. For raw chain data that subgraphs do not index, see the [on-chain data API guide](https://fincodelabs.com/en/blog/on-chain-data-api).

## The Graph subgraph query in Python, tested 27 November 2026

This client uses only the standard library, sends the key as a bearer token, raises on GraphQL `errors`, pins every page to one block and pages with `id_gt`.

```python
import json, os, time, urllib.error, urllib.request

GATEWAY = "https://gateway.thegraph.com/api/subgraphs/id/"
UNISWAP_V3 = "5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV"   # from Uniswap's docs

class SubgraphError(Exception):
    pass

def gql(query, variables, key, sid=UNISWAP_V3, base=GATEWAY, opener=urllib.request.urlopen, tries=3):
    body = json.dumps({"query": query, "variables": variables}).encode()
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}", "User-Agent": "Mozilla/5.0"}
    for attempt in range(tries):
        try:
            with opener(urllib.request.Request(base + sid, body, headers), timeout=30) as r:
                raw = r.read()
        except urllib.error.HTTPError as e:
            if e.code == 429 and attempt < tries - 1:
                time.sleep(2 ** attempt)
                continue
            raise SubgraphError(f"HTTP {e.code}") from None
        except OSError as e:               # DNS, refused, timeout, reset
            raise SubgraphError(f"network error: {getattr(e, 'reason', e)}") from None
        try:
            data = json.loads(raw)
        except ValueError:
            raise SubgraphError(f"not JSON: {repr(raw[:40])}") from None
        if data.get("errors"):           # auth and query errors arrive with HTTP 200
            raise SubgraphError("; ".join(e.get("message", "?") for e in data["errors"]))
        return data["data"]
    raise SubgraphError("gave up after retries")

POOLS = """query($block: Int, $last: Bytes, $n: Int) {
  pools(first: $n, orderBy: id, orderDirection: asc, block: {number: $block}, where: {id_gt: $last}) {
    id feeTier token0 { symbol } token1 { symbol } } }"""

def all_pools(key, n=1000, max_pages=5, **kw):
    block = gql("{ _meta { block { number } } }", {}, key, **kw)["_meta"]["block"]["number"]
    rows, last = [], "0x"
    for _ in range(max_pages):
        page = gql(POOLS, {"block": block, "last": last, "n": n}, key, **kw)["pools"]
        rows += page
        if len(page) < n:
            break
        last = page[-1]["id"]              # cursor: highest id seen so far
    else:
        raise SubgraphError(f"stopped after {max_pages} pages; raise max_pages")
    return block, rows

if __name__ == "__main__":
    for label, key, kw in [("no key", "", {}), ("fake key", "0" * 32, {}),
                           ("network", "0" * 32, {"base": "https://gateway.thegraph.invalid/"})]:
        try:
            print(label, "->", all_pools(key, **kw))
        except SubgraphError as e:
            print(label, "->", e)
```

Real output against the live gateway, without a key:

```
no key -> auth error: invalid authorization header
fake key -> auth error: API key not found
network -> network error: [Errno 11001] getaddrinfo failed
```

The reserved `.invalid` hostname fails at DNS, before any auth check, so it is reported as a network error. The pagination logic and the other failure modes were tested against a simulated gateway that serves five synthetic pool ids:

```python
import io, json, urllib.error
import subgraph_pages as sg
sg.time.sleep = lambda s: None

IDS = ["0x01", "0x02", "0x03", "0x04", "0x05"]       # synthetic pool ids
def fake_gateway(script=None):
    sent = []
    def opener(req, timeout):
        q = json.loads(req.data); sent.append(q["variables"])
        if script:
            status, body = script.pop(0)
            if status >= 400:
                raise urllib.error.HTTPError(req.full_url, status, "", {}, io.BytesIO(body))
            return io.BytesIO(body)
        if "_meta" in q["query"]:
            return io.BytesIO(b'{"data": {"_meta": {"block": {"number": 21000000}}}}')
        v = q["variables"]
        page = [{"id": i, "feeTier": "3000"} for i in IDS if i > v["last"]][: v["n"]]
        return io.BytesIO(json.dumps({"data": {"pools": page}}).encode())
    return opener, sent

opener, sent = fake_gateway()
block, rows = sg.all_pools("test", n=2, opener=opener)
print("block", block, "| rows", [r["id"] for r in rows])
print("cursors sent", [v.get("last") for v in sent[1:]], "| blocks sent", {v.get("block") for v in sent[1:]})
for name, script in {"bad JSON": [(200, b"upstream error")],
                     "429 then auth error": [(429, b""), (200, b'{"errors":[{"message":"auth error: API key not found"}]}')]}.items():
    try:
        sg.gql("{ _meta { block { number } } }", {}, "test", opener=fake_gateway(script)[0])
    except sg.SubgraphError as e:
        print(name, "->", e)
```

Output:

```
block 21000000 | rows ['0x01', '0x02', '0x03', '0x04', '0x05']
cursors sent ['0x', '0x02', '0x04'] | blocks sent {21000000}
bad JSON -> not JSON: b'upstream error'
429 then auth error -> auth error: API key not found
```

The cursor advances by each page's last id, on one block. Not tested: a real query result, because that needs a key. Uniswap v3 pool ids are `Bytes`, so the query declares `$last: Bytes` and starts from `"0x"`; whether the gateway accepts `"0x"` as the first cursor could not be confirmed without a key. If it does not, send the first page without the `id_gt` filter.

## What the subgraph docs do not tell you

A subgraph is an indexer's view of the chain, so its numbers can lag, its schema can change, and its rate limit is not published.

- **Freshness.** Compare `_meta.block.number` with the chain head before acting on a result; a subgraph that has fallen behind still answers.
- **Indexing errors.** `hasIndexingErrors: true` means the data stopped being complete at some block.
- **Derived values.** Fields such as `volumeUSD` are computed by the subgraph's own mapping code, so check against the contract or a block explorer such as the one in the [Etherscan API guide](https://fincodelabs.com/en/blog/etherscan-api) before relying on them.
- **Throttling.** No numeric rate limit was published on the pages read; retry 429 and 5xx with [exponential backoff and jitter](https://fincodelabs.com/en/blog/exponential-backoff-jitter-python).

For readers in Turkey, Article 99/A of Capital Markets Law No. 6362 treats activity by foreign crypto-asset platforms directed at Turkish residents as unauthorized. If you are scoping an indexing or analytics pipeline, Fincode's [market data pipeline service](https://fincodelabs.com/en/services/market-data-pipelines) page describes how such work is scoped; naming The Graph or Uniswap here does not mean Fincode integrates them.

## Frequently asked questions

### Do I need an API key to query The Graph?

Yes, for subgraphs published on The Graph Network. A request without a key returned auth error: missing authorization header on 27 November 2026, with HTTP status 200.

### How much does The Graph API cost?

The first 100,000 queries a month are free and further queries cost $2 per 100,000, payable by card or GRT, per the pricing pages read on 27 November 2026.

### What is the maximum first value in a subgraph query?

1,000 by default on Graph Node, per the GraphQL API reference. Without first, a collection query returns at most 100 entities.

### How do I paginate a subgraph without skip?

Order by id, request first: 1000, and filter the next page with id_gt set to the last id received. Pin every page to the same block number for a consistent snapshot.

### Where do I find the Uniswap v3 subgraph ID?

Uniswap's own subgraph documentation lists it; on 27 November 2026 the v3 mainnet ID was 5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV.

## Sources

- [The Graph docs: How to Query a Subgraph, read 27 November 2026](https://thegraph.com/docs/en/subgraphs/querying/introduction/)
- [The Graph docs: How to Manage API keys](https://thegraph.com/docs/en/subgraphs/querying/managing-api-keys/)
- [The Graph docs: Querying from an Application](https://thegraph.com/docs/en/subgraphs/querying/from-an-application/)
- [The Graph docs: GraphQL API](https://thegraph.com/docs/en/subgraphs/querying/graphql-api/)
- [The Graph docs: Subgraph Studio billing](https://thegraph.com/docs/en/subgraphs/billing/)
- [The Graph: Subgraph Studio pricing, read 27 November 2026](https://thegraph.com/studio-pricing/)
- [The Graph: machine-readable pricing, last updated 28 May 2026](https://thegraph.com/pricing.md)
- [Uniswap docs: Subgraph overview](https://docs.uniswap.org/api/subgraph/overview)
- [Uniswap v3-subgraph repository, schema in src/v3/schema.graphql](https://github.com/Uniswap/v3-subgraph)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/the-graph-subgraph-api

Cite as: Fincode, "The Graph subgraph API: keys, fees and GraphQL in Python", updated November 27, 2026, https://fincodelabs.com/en/blog/the-graph-subgraph-api
