Sub topic 11
Pulling DefiLlama data with the public API
This chapter shows how to fetch DefiLlama's numbers from code instead of reading them off the website. You will call the main endpoints, read the JSON they return, and turn it into daily series you can compare with a Dune query.
It assumes you know:
- Basic Python and the
requestslibrary. - What TVL, DEX volume and stablecoin supply mean (covered in the earlier DefiLlama chapters).
- How to read JSON as nested dictionaries and lists.
Why use the API
The website is good for browsing. The API is better when you need to:
- Repeat the same pull every day without clicking.
- Join DefiLlama figures with your own data, such as a Dune export.
- Check a number on a dashboard against its source.
- Filter or rank protocols in ways the site does not offer.
The core DefiLlama endpoints are public and need no key. Some newer or heavier endpoints sit behind a paid plan on a separate host. The official API documentation lists which endpoints are free and which need a key. Check it before you build on an endpoint, because the lists change.
One API, several hosts
DefiLlama splits its data across several hostnames. Picking the wrong host is the most common first error.
| Data | Host | Example path |
|---|---|---|
| TVL for protocols and chains | `https://api.llama.fi` | `/protocols`, `/v2/chains` |
| DEX volume, fees, revenue | `https://api.llama.fi` | `/overview/dexs`, `/overview/fees` |
| Stablecoins | `https://stablecoins.llama.fi` | `/stablecoins` |
| Yield pools | `https://yields.llama.fi` | `/pools` |
| Token prices | `https://coins.llama.fi` | `/prices/current/{coins}` |
A reusable request helper
Write one small function for every call. It sets a timeout, raises an error on bad HTTP status, and retries on rate limits and server errors.
import time
import requests
session = requests.Session()
session.headers.update({"User-Agent": "onchain-tutorial/1.0"})
def get_json(url, params=None, retries=3):
"""GET a URL and return parsed JSON, retrying on 429 and 5xx."""
for attempt in range(retries):
resp = session.get(url, params=params, timeout=30)
if resp.status_code in (429, 500, 502, 503, 504):
time.sleep(2 ** attempt)
continue
resp.raise_for_status()
return resp.json()
resp.raise_for_status()
data = get_json("https://api.llama.fi/protocols")
print(type(data).__name__, len(data))Without timeout, requests can wait forever. Without raise_for_status(), an error page can reach your parser and fail later with a confusing message.
Listing protocols and their TVL
The /protocols endpoint returns one object per protocol. It is the quickest way to rank the market.
import requests
resp = requests.get("https://api.llama.fi/protocols", timeout=30)
resp.raise_for_status()
protocols = resp.json()
top = sorted(
(p for p in protocols if p.get("tvl")),
key=lambda p: p["tvl"],
reverse=True,
)[:10]
for p in top:
category = p.get("category") or "n/a"
print(f"{p['name']:<25} {category:<20} ${p['tvl'] / 1e9:,.2f}B")Useful fields on each object:
nameandslug. Theslugis the identifier other endpoints expect.category, such as Dexs, Lending or Liquid Staking.chains, a list of chains where the protocol is deployed.tvl, the current value in US dollars.change_1dandchange_7d, percentage changes.
Some entries have tvl set to null or 0. The if p.get("tvl") filter drops them. Use .get() rather than [] for optional fields, because not every protocol has every field.
Historical TVL for a chain
Time series come as lists of points. Dates are Unix timestamps in seconds, in UTC.
from datetime import datetime, timezone
import requests
url = "https://api.llama.fi/v2/historicalChainTvl/Ethereum"
resp = requests.get(url, timeout=30)
resp.raise_for_status()
history = resp.json()
for point in history[-7:]:
day = datetime.fromtimestamp(point["date"], tz=timezone.utc).date()
print(day, f"${point['tvl'] / 1e9:,.2f}B")Convert timestamps with an explicit time zone. Dune's block_date is also a UTC date, so keeping both sources in UTC avoids off-by-one-day mismatches when you cross-check.
Protocol detail and chain breakdown
The /protocol/{slug} endpoint returns more for a single protocol. It includes a daily TVL history and a per-chain breakdown.
from datetime import datetime, timezone
import requests
slug = "aave-v3"
resp = requests.get(f"https://api.llama.fi/protocol/{slug}", timeout=30)
resp.raise_for_status()
detail = resp.json()
print(detail["name"], detail.get("category"))
# Aggregate history: a list of {"date": ..., "totalLiquidityUSD": ...}
last = detail["tvl"][-1]
day = datetime.fromtimestamp(last["date"], tz=timezone.utc).date()
print("Latest point:", day, f"${last['totalLiquidityUSD'] / 1e9:,.2f}B")
# Per-chain history lives under chainTvls
for key, series in detail["chainTvls"].items():
points = series.get("tvl", [])
if points:
print(f"{key:<25} ${points[-1]['totalLiquidityUSD'] / 1e9:,.3f}B")The chainTvls keys are not only chain names. Keys with suffixes such as -borrowed, -staking or -pool2 hold separate series, and borrowed values are not part of headline TVL. If you sum every key, you will overcount. Print the keys first and decide which ones you want.
Volume and fees
DEX volume comes from the overview endpoints. You can filter by chain by adding the chain name to the path.
import requests
url = "https://api.llama.fi/overview/dexs/ethereum"
params = {
"excludeTotalDataChart": "true",
"excludeTotalDataChartBreakdown": "true",
}
resp = requests.get(url, params=params, timeout=30)
resp.raise_for_status()
overview = resp.json()
print("24h volume:", f"${overview['total24h'] / 1e9:,.2f}B")
ranked = sorted(
(p for p in overview["protocols"] if p.get("total24h")),
key=lambda p: p["total24h"],
reverse=True,
)
for p in ranked[:5]:
print(f"{p['name']:<25} ${p['total24h'] / 1e6:,.1f}M")The same shape works for /overview/fees. Fees and revenue are different measures. Fees are what users pay. Revenue is the part the protocol keeps. Read the field names before you compare them with anything.
Stablecoin supply
Stablecoins live on their own host and use their own field names.
import requests
url = "https://stablecoins.llama.fi/stablecoins"
resp = requests.get(url, params={"includePrices": "true"}, timeout=30)
resp.raise_for_status()
assets = resp.json()["peggedAssets"]
def circulating_usd(asset):
return (asset.get("circulating") or {}).get("peggedUSD") or 0
for a in sorted(assets, key=circulating_usd, reverse=True)[:5]:
print(f"{a['symbol']:<8} ${circulating_usd(a) / 1e9:,.1f}B")The peggedUSD key means the supply is of dollar-pegged coins. Euro-pegged or gold-pegged assets use other keys, such as peggedEUR, so a loop over all assets must handle missing keys.
Turning responses into a table
Most analysis is easier in pandas. A list of dictionaries becomes a DataFrame in one call, and you can resample to daily values.
import pandas as pd
import requests
resp = requests.get("https://api.llama.fi/v2/historicalChainTvl/Ethereum", timeout=30)
resp.raise_for_status()
df = pd.DataFrame(resp.json())
df["day"] = pd.to_datetime(df["date"], unit="s", utc=True).dt.date
df = df.set_index("day")[["tvl"]]
print(df.tail())
print("30-day change:", f"{df['tvl'].iloc[-1] / df['tvl'].iloc[-31] - 1:.1%}")Save the raw JSON, or the DataFrame, with a timestamp each time you fetch. DefiLlama can revise history when it fixes an adapter or adds an asset. A saved copy lets you explain why a number changed.
Common errors
- Wrong host. A 404 or an empty response on
/stablecoinsusually means you calledapi.llama.fiinstead ofstablecoins.llama.fi. - Wrong slug.
/protocol/aaveand/protocol/aave-v3are different protocols. Take slugs from the/protocolslist. - Rate limiting. A 429 status means slow down. Fetch the bulk list once, then cache it, instead of calling per protocol in a tight loop.
- Unix seconds versus milliseconds. DefiLlama dates are in seconds. Passing seconds to a function that expects milliseconds gives dates in 1970.
- Null values. Fields can be
null. Arithmetic onNoneraisesTypeError, so guard withor 0or filter first. - Assuming a stable schema. Endpoints can add or rename fields. Access optional fields with
.get()and check the docs when something breaks.
Preparing for cross-checking
The next chapter-level goal is to compare a DefiLlama metric with one you computed on Dune. The API side of that comparison needs three things:
- A daily series in UTC with one value per date.
- A note on what the series includes, such as which chains and whether borrowed amounts are counted.
- The fetch time, so a later revision is not mistaken for an error.
Exercise
You call https://api.llama.fi/stablecoins and get an error page instead of JSON. Your code then fails with a JSON decoding error. Name the two mistakes in the request, and the fix for each.
Show answer
First, the stablecoin data lives on a different host, so the URL should be https://stablecoins.llama.fi/stablecoins. Second, the code did not call resp.raise_for_status() before resp.json(), so the HTTP error was not reported and the page body reached the JSON parser. Fix both by using the correct host and adding raise_for_status() (and a timeout) to every request.
Exercise
A script sums every value under chainTvls for a lending protocol and gets a total higher than the website's TVL. What is the likely cause, and how do you correct it?
Show answer
The chainTvls object includes extra series with suffixes such as -borrowed, -staking or -pool2, which are not part of the headline TVL. Summing all keys counts those amounts too. Print the keys, then sum only the plain chain-name keys, or use the protocol's aggregate tvl series.