Sub topic 11
Pulling DefiLlama Data with the Public API
This chapter assumes that you know basic Python, can read JSON, and understand that total value locked (TVL) is an estimate of assets counted by a protocol or chain. You do not need to use Dune for the examples here.
How the API works
DefiLlama provides HTTP endpoints that return structured data. Your program sends a request to an endpoint, receives a response, and decodes the response as JSON. JSON is a text format for objects, arrays, strings, numbers, and Boolean values.
The /protocols endpoint returns a list of protocols. Each protocol is represented by an object with fields such as:
| Field | Meaning |
|---|---|
| `name` | Display name of the protocol |
| `category` | Protocol category, such as Lending or Dexes |
| `tvl` | Current TVL value, usually in US dollars |
| `chains` | Chains on which the protocol is tracked |
A response is a snapshot. It can change as prices, balances, and DefiLlama's tracking data change.
Fetching and filtering protocols
The following program requests the protocol list, checks for an HTTP error, and prints the ten protocols with the highest reported TVL.
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")requests.get performs the HTTP request. The timeout prevents the program from waiting forever if the service does not respond. raise_for_status turns an HTTP failure, such as a 404 or 500 response, into an exception.
The generator inside sorted skips objects without a usable tvl field. The key argument tells Python which value to compare. Dividing by 1e9 changes dollars into billions for easier reading.
Choosing an endpoint
DefiLlama exposes endpoints for different kinds of measurements. Common examples include protocol TVL, historical protocol TVL, chain TVL, decentralized exchange volume, fees, yields, and stablecoins. Endpoint paths and response fields differ, so inspect the endpoint's current documentation before writing a parser.
A useful workflow is:
- Request a small or current dataset.
- Print one response object.
- Identify the fields and their units.
- Add filtering and aggregation only after you understand the shape.
- Save the raw response when reproducibility matters.
The data flow looks like this:
Reliable API scripts
Treat external data as incomplete. Use get for optional fields, check that numeric values are present, and record the retrieval time if you publish the result. For repeated collection, handle connection errors and avoid sending unnecessary requests. Cache responses when the same snapshot can serve several calculations.
The API gives you data, not a complete explanation of its methodology. For a serious comparison, record the endpoint, retrieval time, filters, units, and any exclusions. Then compare those details with the dashboard's methodology.
Exercise
Why does the example call raise_for_status() before decoding the response as JSON?
Show answer
It detects an HTTP failure early, so the program does not mistake an error page or error object for the expected protocol list.