DEV Community

Julien
Julien

Posted on

How I Built a DeFi Yield Dashboard in 50 Lines of Python

How I Built a DeFi Yield Dashboard in 50 Lines of Python

I wanted a simple dashboard that shows me the best yield farming opportunities across DeFi — without logging into five different apps, without switching chains, and without guessing which pools are legit. So I built one in an afternoon using a DeFi API tutorial approach that I'm going to share with you.

The best part? The entire thing is under 50 lines of Python. Let me show you how.


The Problem With Yield Data

If you've ever tried to compare DeFi yields across protocols, you know the pain:

  • You check Aave's app for stablecoin yields
  • You hop over to Curve to see pool APYs
  • You open another tab for Compound rates
  • Then you realize you forgot to check Arbitrum and Optimism

By the time you've gathered all the data, rates have already changed. What you need is a single source of truth that aggregates yields across protocols and chains.

That's exactly what I found when I discovered the DeFi Data API on RapidAPI. It gives you a /yields/top endpoint that returns the highest-yielding pools across all of DeFi in one call.


What You'll Need

Before we start coding, here's what you need:

  • Python 3.8+
  • The requests library (pip install requests)
  • A free RapidAPI account with the DeFi Data API subscribed

That's it. No databases, no frontend framework, no complex setup.


Step 1: Set Up the API Client

First, let's create a simple client to talk to the DeFi Data API. The base URL is https://defi-api-425658670453.europe-west1.run.app and authentication is handled through the standard RapidAPI header.

import requests

RAPIDAPI_KEY = "YOUR_RAPIDAPI_KEY"
BASE_URL = "https://defi-api-425658670453.europe-west1.run.app"
HEADERS = {
    "X-RapidAPI-Key": RAPIDAPI_KEY,
    "X-RapidAPI-Host": "defi-data-api"
}
Enter fullscreen mode Exit fullscreen mode

This pattern should look familiar if you've used any RapidAPI listing before. Replace YOUR_RAPIDAPI_KEY with your actual key from the RapidAPI dashboard.


Step 2: Fetch Top Yields

Now for the core of our dashboard — fetching the top yield opportunities:

def get_top_yields(limit=20):
    """Fetch the top yielding DeFi pools."""
    response = requests.get(f"{BASE_URL}/yields/top", headers=HEADERS)
    response.raise_for_status()
    return response.json()[:limit]
Enter fullscreen mode Exit fullscreen mode

One call, and you get a ranked list of the highest APY pools across all of DeFi. Each entry includes the pool name, APY, TVL, chain, and protocol. No stitching together five different endpoints.


Step 3: Fetch Chain and Protocol Context

Yields don't mean much without context. A 50% APY on a pool with $5,000 TVL is very different from 15% on a pool with $500 million. Let's also pull chain-level data to give us a bigger picture:

def get_chain_stats():
    """Get TVL stats by chain."""
    response = requests.get(f"{BASE_URL}/chains", headers=HEADERS)
    response.raise_for_status()
    return response.json()

def get_protocol(slug):
    """Get detailed protocol info."""
    response = requests.get(f"{BASE_URL}/protocols/{slug}", headers=HEADERS)
    response.raise_for_status()
    return response.json()
Enter fullscreen mode Exit fullscreen mode

These helper functions give us the context we need to make informed decisions about which yields are actually worth pursuing.


Step 4: Build the Dashboard

Now let's put it all together. Here's the complete dashboard in about 50 lines:

import requests

RAPIDAPI_KEY = "YOUR_RAPIDAPI_KEY"
BASE_URL = "https://defi-api-425658670453.europe-west1.run.app"
HEADERS = {
    "X-RapidAPI-Key": RAPIDAPI_KEY,
    "X-RapidAPI-Host": "defi-data-api"
}

def api_get(endpoint):
    r = requests.get(f"{BASE_URL}{endpoint}", headers=HEADERS)
    r.raise_for_status()
    return r.json()

def main():
    # 1. Fetch top yields
    yields = api_get("/yields/top")

    # 2. Fetch chain stats
    chains = api_get("/chains")
    chain_tvl = {c.get("name"): c.get("tvl", 0) for c in chains}

    # 3. Display header
    print("=" * 70)
    print("  DEFI YIELD DASHBOARD")
    print("=" * 70)

    # 4. Top chains by TVL
    print("\n📊 Top Chains by TVL:")
    sorted_chains = sorted(chain_tvl.items(), key=lambda x: x[1], reverse=True)[:5]
    for chain, tvl in sorted_chains:
        print(f"   {chain:<15} ${tvl:>15,.0f}")

    # 5. Top yield pools (TVL-filtered: only pools with > $1M TVL)
    print("\n🌾 Top Yield Opportunities (TVL > $1M):")
    print(f"   {'Pool':<30} {'APY':>8} {'TVL':>15} {'Chain':<12}")
    print("   " + "-" * 65)

    safe_yields = [
        y for y in yields
        if y.get("tvlUsd", 0) > 1_000_000
    ][:15]

    for pool in safe_yields:
        symbol = pool.get("symbol", "Unknown")[:28]
        apy = pool.get("apy", 0)
        tvl = pool.get("tvlUsd", 0)
        chain = pool.get("chain", "Unknown")
        print(f"   {symbol:<30} {apy:>7.2f}% ${tvl:>14,.0f} {chain:<12}")

    # 6. Quick stats
    print(f"\n📈 Total pools analyzed: {len(yields)}")
    avg_apy = sum(y.get("apy", 0) for y in safe_yields) / max(len(safe_yields), 1)
    print(f"📊 Average APY (top pools): {avg_apy:.2f}%")
    print("=" * 70)

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Run this with python dashboard.py and you'll get a clean, formatted output showing the top chains by TVL and the best yield opportunities filtered for safety (pools with over $1M TVL).


Sample Output

When you run this, you'll see something like:

======================================================================
  DEFI YIELD DASHBOARD
======================================================================

📊 Top Chains by TVL:
   Ethereum         $   45,230,000,000
   Tron             $    8,100,000,000
   BSC              $    5,200,000,000
   Arbitrum         $    3,900,000,000
   Polygon          $    1,800,000,000

🌾 Top Yield Opportunities (TVL > $1M):
   Pool                              APY               TVL Chain
   -----------------------------------------------------------------
   stETH/ETH                       3.45% $  1,200,000,000 Ethereum
   USDC/USDT                       5.12% $    850,000,000 Ethereum
   WBTC/ETH                        4.80% $    620,000,000 Arbitrum

📈 Total pools analyzed: 100
📊 Average APY (top pools): 4.56%
======================================================================
Enter fullscreen mode Exit fullscreen mode

Going Further: Add Protocol Deep Dives

The dashboard above is a great starting point. If you see a pool that interests you, you can drill into the protocol with a single additional call:

# Deep dive into a specific protocol
protocol = api_get("/protocols/aave")

print(f"\nProtocol: {protocol['name']}")
print(f"Category: {protocol.get('category', 'N/A')}")
print(f"TVL: ${protocol.get('tvl', 0):,.0f}")
print(f"Chains: {', '.join(protocol.get('chains', []))}")
Enter fullscreen mode Exit fullscreen mode

This gives you the full picture: what the protocol does, where it operates, and how much capital it manages.


Why I Chose the DeFi Data API

I could have used DeFiLlama's open API or scraped individual protocol websites. But for a yield farming API use case, I wanted:

  1. One endpoint for yields — no need to aggregate from multiple sources
  2. Protocol metadata — so I can filter and categorize
  3. Chain-level stats — for the bigger picture
  4. Consistent JSON format — every response follows the same structure

The DeFi Data API on RapidAPI checked all four boxes. It's not the only option out there, but for building a quick yield dashboard in Python, it's hard to beat the simplicity.

You can find it by searching "DeFi Data API" on RapidAPI — the free tier handles everything I've shown here.


Possible Extensions

Once you have this foundation, here are some ways to extend it:

  • Add alerts: Use the data to send yourself Telegram or Discord notifications when a yield crosses a threshold
  • Historical tracking: Store results in a SQLite database and plot APY trends over time with matplotlib
  • Web interface: Wrap the dashboard in a Streamlit app for a browser-based UI
  • Multi-chain filtering: Let the user filter by chain, category, or minimum TVL

The API also has /stats and /categories endpoints that I haven't even touched here. There's plenty of room to build something more sophisticated.


Wrapping Up

Building a DeFi yield dashboard in Python doesn't have to be complicated. With the right API, 50 lines of code is enough to go from zero to a functional tool that surfaces real opportunities.

The key takeaway: don't over-engineer it. Start with a simple script that solves your problem, then iterate. The DeFi Data API on RapidAPI gives you everything you need to start prototyping immediately.

If you build something cool with this, I'd love to hear about it. Drop a comment below or find me on socials. Happy coding! 🐍


This article is part of a series on building DeFi tools with Python. Follow for more tutorials like this one.

Top comments (0)