Build an Agent That Pays for Its Own APIs — in 50 Lines of Python

📅 August 10, 2026 🏷️ Developer Guide ⏱️ 8 min read

Most "agent payments" articles talk about infrastructure. This one is different. You're going to build a working agent — right now — that discovers APIs, tries them for free, and pays with real USDC when it finds one worth using. All in 50 lines of Python.

No API keys. No signup forms. No KYC. Just HTTP.

What you'll build: An agent that searches for gas prices across chains, tries the endpoint for free, handles the payment gate, and makes a real paid call — all without human intervention.

The Architecture in 3 Steps

STEP 1

Discover: Ask the marketplace what's available

Your agent starts by asking: "What APIs exist, and which ones are actually working?" The marketplace responds with 317 live services, each with pricing and trial availability.

import requests, json

# Discover available APIs
r = requests.get("https://minia2a.uk/api/services")
market = r.json()
print(f"Found {market['count']} services")

# Find gas-related endpoints
gas_apis = [s for s in market['services']
            if 'gas' in s['id'].lower() and s['active']]
for api in gas_apis:
    print(f"  {api['id']}: ${api['priceCents']/100:.2f}/call — {api['description'][:60]}")
STEP 2

Try: Use the free trial before spending a cent

This is the part most payment systems get wrong. Your agent shouldn't pay for something it hasn't tested. Append ?trial=1 to any endpoint — the marketplace gives you up to 15 free calls per service. No wallet, no registration, no commitment.

def try_endpoint(endpoint_url, payload=None):
    """Call any endpoint with trial=1 for a free test."""
    trial_url = f"{endpoint_url}?trial=1"
    r = requests.post(trial_url, json=payload or {})
    return r.json()

# Try the gas endpoint
result = try_endpoint("https://minia2a.uk/x402/gas", {"chain": "ethereum"})
print(json.dumps(result, indent=2))

The response tells your agent whether the trial was accepted (HTTP 200 + "_trial": true) or whether it needs to register for more credits.

STEP 3

Pay: When the API is worth it, spend USDC

After testing, your agent decides: is this API worth paying for? If yes, it registers (one POST — gets 500 free credits), then spends them on the endpoints it needs. The credits are real USDC on Base, managed by the marketplace. Your agent never touches a private key.

def pay_and_call(endpoint_url, wallet, payload=None):
    """Make a paid call using wallet credits."""
    r = requests.post(
        endpoint_url,
        json=payload or {},
        headers={"Authorization": f"Bearer {wallet}"}
    )
    if r.status_code == 200:
        data = r.json()
        print(f"✅ Paid call succeeded. Remaining credits: {data.get('credits_remaining')}")
        return data
    elif r.status_code == 402:
        print(f"💳 Payment required: {r.json().get('message')}")
        return None

# Your agent's wallet (from registration)
wallet = "0x..."
result = pay_and_call("https://minia2a.uk/x402/gas", wallet, {"chain": "ethereum"})

The Complete Agent (All 50 Lines)

Here's the whole thing. Copy, paste, run:

#!/usr/bin/env python3
"""Agent that discovers, tries, and pays for APIs — full autonomous loop."""
import requests, json, os, time

MARKETPLACE = "https://minia2a.uk"
WALLET_FILE = ".agent-wallet.json"

def load_or_register():
    """Load existing wallet or register a new one."""
    if os.path.exists(WALLET_FILE):
        return json.load(open(WALLET_FILE))
    r = requests.post(f"{MARKETPLACE}/api/v1/register-simple",
                      json={"name": "builder-agent"})
    wallet = r.json()
    json.dump(wallet, open(WALLET_FILE, 'w'))
    print(f"🆕 Registered! Wallet: {wallet['wallet'][:10]}... "
          f"Credits: {wallet.get('credits', 500)}")
    return wallet

def discover_apis():
    """Fetch and filter live APIs."""
    r = requests.get(f"{MARKETPLACE}/api/services")
    svcs = r.json()['services']
    return [s for s in svcs if s.get('active')]

def try_or_pay(endpoint, wallet=None):
    """Trial-first: try free, pay if needed."""
    # Step 1: Free trial
    r = requests.post(f"{endpoint}?trial=1", json={})
    if r.status_code == 200 and r.json().get('_trial'):
        return {"free": True, "data": r.json()}

    # Step 2: Pay with credits
    if wallet:
        r = requests.post(endpoint, json={},
                         headers={"Authorization": f"Bearer {wallet['wallet']}"})
        if r.status_code == 200:
            remaining = r.json().get('credits_remaining', '?')
            return {"free": False, "data": r.json(), "credits_left": remaining}
    return None

# ── Main agent loop ──
wallet = load_or_register()
apis = discover_apis()
print(f"📡 {len(apis)} live APIs found")

for api in apis[:5]:  # Try top 5
    result = try_or_pay(api['endpoint'], wallet)
    if result:
        label = "🆓 FREE trial" if result['free'] else "💳 PAID call"
        print(f"{label} → {api['id']} (${api['priceCents']/100:.2f})")
    time.sleep(0.5)

print("✅ Agent run complete.")

What Happens When You Run It

$ python3 agent.py
🆕 Registered! Wallet: 0xf16F0882... Credits: 500
📡 317 live APIs found
🆓 FREE trial → x402-recall ($0.01)
🆓 FREE trial → x402-gas ($0.01)
🆓 FREE trial → x402-captcha-solve ($0.00)
🆓 FREE trial → x402-find ($0.01)
🆓 FREE trial → x402-polymarket ($0.01)
✅ Agent run complete.

Your agent just discovered 317 APIs, tried 5 for free, and is ready to pay for any it finds useful — all without a human touching a signup form or API key dashboard.

Why Trial-First Changes Everything

Traditional API marketplaces work like this: find an API → read docs → create account → get API key → add payment method → make first call. That's 6 steps before your agent gets any value back. Most agents never complete step 3.

The trial-first flow is different:

  1. Agent finds an API — marketplace returns all 317 services with pricing
  2. Agent tries it free?trial=1 gives up to 15 free calls per endpoint, no questions asked
  3. Agent decides if it's worth paying — based on real data, not marketing copy
  4. Agent registers once — one POST, gets 500 credits, never touches a private key
  5. Agent pays per callAuthorization: Bearer {wallet}, credits deducted automatically

This is the flow that makes agent-to-agent commerce work. Agents can't fill out signup forms. They can't solve CAPTCHAs. They can't wait for "account approval." They need to discover → try → pay in a single HTTP request/response cycle. That's what this architecture enables.

The Bigger Picture: Why This Matters Now

August 2026 has been the busiest month in agent payment history:

The infrastructure is being built at an extraordinary pace. Cloudflare, Mastercard, Visa, Stripe, and now Zero Hash — every major financial infrastructure player is shipping agent payment products this month.

But here's the thing: all of this is payment rails. None of it helps an agent figure out which of the 35,000+ x402 endpoints are actually worth paying for.

The discovery layer — the part your 50-line agent uses — is the bottleneck. And the trial-first pattern is the unlock: let agents test before they commit, surface the endpoints that actually work, and make the jump from "I can pay" to "I know what to pay for" in a single HTTP call.

What To Build Next

Your agent now has the basic loop. Here's where to take it:

  1. Add a quality filter — track which endpoints respond fastest and most reliably. Prefer ones with low error rates.
  2. Add a budget guard — read a .agent-budget file (proposed standard: {"daily_limit_usdc": 5, "max_per_call_usdc": 1}) and refuse calls that would exceed it.
  3. Add multi-endpoint fallback — if the gas endpoint fails, try the next gas-related endpoint. Agents should be resilient.
  4. Add receipt verification — store the x402-receipt header from paid responses. You'll want it if you ever need to dispute a charge.

Ready to build an agent that pays for itself?

317 APIs, 15 free trials each, no signup required. Your agent can be paying for its own API calls in 5 minutes.

Browse Live APIs →

Real Numbers (August 10, 2026)

This isn't a demo. The marketplace is live with real usage:

The infrastructure works. The payment rails are here. The missing piece is agents that know how to use them — and that's what you just built.