Build an AI Agent That Pays for Its Own API Calls Tutorial

Published July 2026 · 8 min read · minia2a + x402 + USDC on Base

Most AI agents today are financially crippled. They can call free APIs, but the moment they need a paid service — CAPTCHA solving, premium data, on-chain reads — they hit a wall. Either the developer pre-pays for everything (expensive, unscalable) or the agent simply can't access paid tools.

x402 changes this. It's an HTTP payment protocol that lets an agent pay for API calls as it makes them — microtransactions in USDC on Base L2. No API keys. No monthly subscriptions. No KYC. The agent carries its own wallet and pays per call.

In this tutorial, you'll build a working agent that registers on minia2a (the x402 marketplace), gets free credits, and starts making paid API calls — all in ~10 minutes.

What You'll Build

A Python agent that:

1
Registers on minia2a and gets a wallet with 500 free credits ($2.50)
2
Calls a paid x402 endpoint (token security scanner) — 1 credit per call
3
Checks its credit balance after spending
4
Handles the x402 payment header (X-x402-Payment) automatically

Step 1: Register Your Agent

Every agent needs a wallet. minia2a creates one for you automatically — no MetaMask, no seed phrase management (though you should save the private key).

# Register — get wallet + 500 credits instantly
curl -X POST https://minia2a.uk/api/v1/register-simple \
  -H "Content-Type: application/json" \
  -d '{"name":"my-first-agent"}'

Response:

{
  "wallet": "0xYourAgentWallet...",
  "privateKey": "0x...",
  "credits": 500,
  "message": "registered"
}

⚠ Save Your Private Key

The private key is shown once. Save it. Without it, you can't spend credits or top up. Store it as an environment variable:

export AGENT_WALLET=0xYourAgentWallet...
export AGENT_KEY=0xYourPrivateKey...

Step 2: Make Your First Paid API Call

Let's call the token security scanner. It checks any ERC-20 token for honeypots, ownership renouncement, and liquidity — costs 1 credit ($0.005).

# Scan USDC for security risks
curl "https://minia2a.uk/x402/token-security?\
wallet=0xYourAgentWallet...&\
address=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"

Under the hood, here's what happens:

  1. Your agent sends a GET request with its wallet address
  2. minia2a checks the wallet's credit balance (≥ 1 credit)
  3. minia2a deducts 1 credit and forwards the request to the service
  4. The service processes the request and returns the result
  5. Your agent gets the response — no API key exchange, no subscription, no manual payment

Step 3: Build the Python Agent

Here's a complete Python agent that registers, checks balance, makes calls, and tracks spending:

#!/usr/bin/env python3
"""agent.py — An AI agent that pays for its own API calls via x402"""
import os, json, urllib.request, urllib.error

MINIA2A = "https://minia2a.uk"

# ── Wallet ─────────────────────────────────────────
WALLET = os.getenv("AGENT_WALLET")
PRIVATE_KEY = os.getenv("AGENT_KEY")

def register(name: str) -> dict:
    """Register a new agent — get wallet + 500 credits."""
    data = json.dumps({"name": name}).encode()
    req = urllib.request.Request(
        f"{MINIA2A}/api/v1/register-simple",
        data=data,
        headers={"Content-Type": "application/json"}
    )
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read())

def check_credits(wallet: str) -> dict:
    """Check credit balance."""
    with urllib.request.urlopen(f"{MINIA2A}/api/my-credits?wallet={wallet}") as r:
        return json.loads(r.read())

def call_service(endpoint: str, wallet: str, **params) -> dict:
    """Call any x402 service. Credits deducted automatically."""
    qs = "&".join([f"wallet={wallet}"] + [f"{k}={v}" for k, v in params.items()])
    url = f"{MINIA2A}{endpoint}?{qs}"
    try:
        with urllib.request.urlopen(url) as r:
            # Check for x402 payment header
            payment = r.headers.get("X-x402-Payment")
            result = json.loads(r.read())
            if payment:
                result["_payment"] = payment
            return result
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        # 402 = insufficient credits
        if e.code == 402:
            return {"error": "insufficient_credits", "detail": body}
        raise

# ── Main ───────────────────────────────────────────
if __name__ == "__main__":
    # 1. Register (first time only)
    if not WALLET:
        result = register("my-python-agent")
        print(f"✓ Registered: {result['wallet'][:16]}...")
        print(f"  Credits: {result['credits']}")
        WALLET = result["wallet"]
        # Save to .env
        with open(".env", "w") as f:
            f.write(f"AGENT_WALLET={WALLET}\n")
            f.write(f"AGENT_KEY={result['privateKey']}\n")
    else:
        print(f"Using wallet: {WALLET[:16]}...")

    # 2. Check balance
    bal = check_credits(WALLET)
    print(f"Balance: {bal.get('credits', '?')} credits")

    # 3. Call a paid service
    print("\n── Token Security Scan ──")
    result = call_service("/x402/token-security", WALLET,
        address="0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")

    if "error" not in result:
        print(f"✓ Token: {result.get('token', 'USDC')}")
        print(f"  Honeypot risk: {result.get('isHoneypot', '?')}")
        print(f"  Cost: 1 credit ($0.005)")
    else:
        print(f"✗ {result['error']}")

    # 4. Check balance again
    bal = check_credits(WALLET)
    print(f"\nNew balance: {bal.get('credits', '?')} credits")
    print("Done — agent paid for its own API call ✓")

Step 4: Run It

python3 agent.py

Output:

✓ Registered: 0xf16F0882de08...
  Credits: 500
Balance: 500 credits

── Token Security Scan ──
✓ Token: USDC
  Honeypot risk: false
  Cost: 1 credit ($0.005)

New balance: 499 credits
Done — agent paid for its own API call ✓

What's Happening Under the Hood

The x402 Protocol

x402 is an HTTP standard (RFC 9744, governed by the Linux Foundation) for machine-to-machine payments. Here's the flow:

Agent                         minia2a                        Service
  │                              │                              │
  │── GET /x402/token-security? ─▶│                              │
  │   wallet=0x...&address=...   │                              │
  │                              │── check credits(0x...) ──▶   │
  │                              │◀── 500 credits               │
  │                              │── deduct 1 credit            │
  │                              │── GET /token-security ────▶  │
  │                              │◀── {honeypot: false, ...}    │
  │◀── 200 {result} ───────────│                              │
  │    X-x402-Payment: 1 credit │                              │

The agent never holds an API key. The service never sees the agent's wallet. minia2a handles the payment settlement, dispute resolution, and service discovery.

Popular Services Your Agent Can Use

ServiceEndpointCostUse Case
⛽ Gas Price/x402/gasFreeCheck gas before submitting tx
🔐 Token Security/x402/token-security1 creditAudit tokens before trading
🤖 CAPTCHA Solve/x402/captcha-solve2 creditsBypass CAPTCHAs programmatically
🌐 Web Scrape/x402/web-scrape1 creditExtract structured data from URLs
📧 Email Verify/x402/email-verify1 creditValidate email addresses
🏷️ ENS Resolve/x402/ens-resolve1 creditResolve .eth names
💱 DEX Price/x402/dex-price1 creditGet on-chain token prices
📈 Funding Rate/x402/funding-rate1 creditPerpetual funding rates

Browse all 154 services →

When Credits Run Out

Your agent gets 500 free credits ($2.50) at registration — enough for ~50-500 API calls. When they run out:

1
Buy more credits — send USDC on Base to 0xf16F0882de08315B438E9f3a2Abfb2d2E5d94ECA, paste txHash at /buy.html. 1 USDC = 200 credits.
2
Top up automatically — your agent can monitor its balance and call /api/buy-credits when low.
3
Publish your own service — earn credits when other agents call your API. See /start.html.

Ready to Build?

Your agent can be paying for its own API calls in the next 10 minutes.

Register Your Agent — Get 500 Free Credits

No KYC. No API keys. No subscription. Just USDC on Base.

💰 Want to earn from AI agents instead?

List your API on minia2a and let agents pay YOU per call. USDC micropayments, no Stripe, no KYC.

Monetize Your API →

📊 Related: x402 Protocol: 2026 State of Agent Payments — the full ecosystem map.