๐Ÿ“… Historical page. This content reflects minia2a as of its publication date and is kept for the record. Current model: x402 pay-per-call in USDC on Base only, 5 free trial calls per signed wallet, no credits and no top-up rail. โ†’ See current

Build Your First x402-Powered AI Agent

Discover, call, and pay for APIs โ€” all from your agent, no API keys required

August 1, 2026 ยท 8 min read ยท by Iris @ minia2a

You've built an AI agent. It can reason, use tools, and interact with the world. But there's one thing it can't do: pay for the APIs it needs. Every useful API โ€” weather, crypto prices, captcha solving, web scraping โ€” requires an API key that a human had to register, verify, and fund.

x402 changes this. It's a protocol that lets your agent pay for API calls automatically, in USDC, at the moment of use. No API keys. No monthly subscriptions. No human in the loop.

In this tutorial, you'll build an agent that discovers services on minia2a.uk (a marketplace of 1,600+ x402 services), signs trial calls with a self-custody wallet to get 5 free calls, and falls through to real x402 settlement when they run out. All running on your machine.

How x402 Works (30-Second Version)

1. Your agent makes an HTTP request to an x402 endpoint.
2. The server responds with 402 Payment Required + a list of payment offers (accepts[]) โ€” each with an amount, network, and pay-to address.
3. Your agent (or the x402 SDK) settles the chosen offer in USDC through a facilitator โ€” ~1 second on Base L2, sub-cent gas.
4. Your agent retries the request, this time with a PAYMENT-SIGNATURE header proving settlement.
5. The server verifies settlement and returns the result.

That's it. Five steps. No OAuth dance, no credit card form, no email verification. Machine-to-machine payments, fully automated.

minia2a has two rails, and they are not interchangeable. Trial: every signed wallet gets 5 free calls, shared across all services, with no registration โ€” you sign the request itself. Paid: real x402 settlement in USDC, with no wallet param at all. For production, drive the second rail with @x402/fetch.

What You'll Build

An agent that:

Prerequisites

Step 1: Discover Services on minia2a

1 Browse the marketplace

minia2a.uk lists every x402 service with its endpoint, price, and description. Browse at minia2a.uk, or query programmatically:

import requests

d = requests.get("https://minia2a.uk/api/services").json()
print(f"{d['count']} services available")

for s in d['services'][:5]:
    print(f"  {s['id']}: ${s['price']:.2f} โ€” {s['description'][:60]}")
    # reliability label: excellent / good / fair / poor / unproven
    print(f"      reliability: {s['reliabilityLabel']} ({s['reliability']})")

Step 2: Try It Free (5 Free Trial Calls)

2 Call an endpoint without any setup

Call the endpoint with no arguments and you get a 402 โ€” not an error, a menu. The body carries a machine-readable accepts[] list and a nextSteps array spelling out both ways forward:

curl -s https://minia2a.uk/x402/time
# HTTP 402
# {"error": "Payment required",
#  "message": "Free trial calls are wallet-based โ€” attach your wallet with a signature to get
#              5 free trial calls (no registration), or pay via x402.",
#  "nextSteps": [
#    "1. Trial: add ?wallet=0xYOUR_WALLET plus headers X-Wallet-Signature=sign(\"minia2a
#        trial:\"+wallet+\":\"+service+\":\"+ts) and X-Trial-Timestamp=ts (unix sec, ยฑ5min)
#        โ€” 5 free calls per wallet, no registration",
#    "2. Pay: include PAYMENT-SIGNATURE (V2) or X-PAYMENT (V1) header", ...],
#  "accepts": [{"amount": "100000", "network": "eip155:8453", "payTo": "0xAb62โ€ฆ", ...}]}

Read that carefully: the free trial is wallet-based, not IP-based, and needs no registration. But you do have to prove you hold the wallet โ€” that is what the two headers above are for. A bare ?wallet= with no signature is a hard 400, not a trial.

Step 3: Register a Wallet โ†’ 5 Free Trials

3 Self-custody: you bring the wallet, you keep the keys

Registration never generates or holds a wallet for you. You sign a message proving you control an address. Be clear on what it buys: identity and publishing, not trials โ€” trials are already wallet-based and need no registration. Register when your agent needs a name on the marketplace:

import os
from eth_account import Account
from eth_account.messages import encode_defunct

PRIVATE_KEY = os.environ["AGENT_WALLET_KEY"]   # never hardcode
account = Account.from_key(PRIVATE_KEY)

# EIP-191 personal_sign of the exact message:
message = f"minia2a register: {account.address}"
signature = account.sign_message(encode_defunct(text=message)).signature.hex()

resp = requests.post("https://minia2a.uk/api/v1/register-simple", json={
    "name": "my-first-agent",
    "wallet": account.address,
    "signature": signature,
})
body = resp.json()
print(body["ok"], body["message"])
# โ†’ True Registered. No credits included โ€” pay per call via x402. (Free trials are
#   wallet-based: any signed wallet gets 5 trial calls, no registration needed.)

โœ“ One free registration per IP. Your wallet address is your account โ€” save it.

Step 4: Call Services With a Signed Trial

4 Sign each call โ€” the trial is per wallet, not per IP

The signature is not a one-time login: it covers this request, so you build it per call. The message binds the wallet, the service id and a fresh timestamp, and that same timestamp rides along in its own header:

import time

def trial_call(service_id: str, **params):
    """One signed trial call โ€” spends one of the wallet's 5 free calls."""
    ts = int(time.time())
    message = f"minia2a trial:{account.address}:{service_id}:{ts}"
    signature = account.sign_message(encode_defunct(text=message)).signature.hex()

    return requests.get(
        f"https://minia2a.uk/x402/{service_id.removeprefix('x402-')}",
        params={"wallet": account.address, **params},
        headers={
            "X-Wallet-Signature": signature,
            "X-Trial-Timestamp": str(ts),
        },
    )

r = trial_call("x402-time")
print(r.status_code, r.headers.get("x-trial-remaining"), r.json())
# โ†’ 200 4 {'ok': True, 'utc': '2026-09-12T12:25:21.940Z', 'unix': 1789215921,
#          'ms': 1789215921940, 'iso': '2026-09-12T12:25:21.940Z', 'timezone': 'UTC'}

Two things are easy to get wrong here. The URL path takes the short slug (time) while the signed message takes the catalog id (x402-time) โ€” sign the wrong one and you get a 400. And the number in X-Trial-Timestamp must be the same integer you signed, within ยฑ5 minutes of server time.

When the 5 calls are spent, the same request returns 402 with trialExhausted: true. That is your signal to settle on-chain โ€” re-signing will not help.

The Complete Agent Loop

Wrap this in a reusable helper your agent can call whenever it needs a service:

import os, time, requests
from eth_account import Account
from eth_account.messages import encode_defunct

class X402Agent:
    """An AI agent that pays for x402 APIs automatically: signed trial, then on-chain."""

    BASE = "https://minia2a.uk"

    def __init__(self, private_key: str):
        self.account = Account.from_key(private_key)

    def call(self, service_id: str, **params) -> dict:
        """Signed trial call. Returns a 402 challenge once the trial is spent."""
        ts = int(time.time())
        message = f"minia2a trial:{self.account.address}:{service_id}:{ts}"
        signature = self.account.sign_message(encode_defunct(text=message)).signature.hex()

        resp = requests.get(
            f"{self.BASE}/x402/{service_id.removeprefix('x402-')}",
            params={"wallet": self.account.address, **params},
            headers={"X-Wallet-Signature": signature, "X-Trial-Timestamp": str(ts)},
        )
        if resp.status_code == 200:
            return {"ok": True, "data": resp.json()}
        # 402 = trial spent, or the endpoint is payment-only. Settle on-chain to continue.
        return {"ok": False, "status": resp.status_code, "body": resp.json()}


# --- Usage ---
agent = X402Agent(os.environ["AGENT_WALLET_KEY"])

# Discover what's available
services = requests.get(f"{X402Agent.BASE}/api/services").json()
print(f"Connected to minia2a โ€” {services['count']} services available")

# Call a service
result = agent.call("x402-time")
print(result["data"] if result["ok"] else f"Error: {result}")

Go Production: Real x402 On-Chain Payments

For production agents that settle in real USDC on-chain (no prepaid credits), use the official @x402/fetch SDK. It detects the 402, reads the accepts[] offers, settles through a facilitator, and retries with the proof header โ€” your code never sees a payment:

npm install @x402/fetch @x402/evm viem
import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.PRIVATE_KEY);

const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{
    network: "eip155:8453",   // Base mainnet
    client: new ExactEvmScheme(account),
  }],
});

// fetchWithPayment handles 402 โ†’ settle โ†’ retry automatically
const gas = await fetchWithPayment("https://minia2a.uk/x402/gas");
console.log(await gas.json());

What Services Can Your Agent Use?

minia2a.uk has 1,600+ services across 20 categories โ€” crypto data, AI inference, web scraping, security, finance, dev tools, and more. Every listing shows its exact price. Here are a few examples:

EndpointWhat It DoesCategory
/x402/timeAccurate UTC timestamptools
/x402/gasReal-time gas prices across chainscrypto
/x402/web-scrapeScrape any webpage, return clean textweb
/x402/token-securityAudit any ERC-20 token for riskssecurity
/x402/sentimentSentiment analysis on any textai

Browse all 1,600+ services โ†’

Why This Matters

The traditional API economy runs on monthly subscriptions and API keys โ€” a model designed for humans. But AI agents don't have email addresses. They can't sign up for Stripe. They can't click "I am not a robot."

x402 is the payment layer for the machine economy. When your agent can pay for API calls directly, you unlock:

Next Steps

  1. Make a signed trial call โ€” any wallet gets 5 free calls with no registration (Step 4). Register when you want a name on the marketplace
  2. Explore the marketplace โ€” find services your agent can use
  3. List your own API โ€” if you've built something useful, monetize it with x402
  4. Read the x402 spec at x402.org for the full protocol details

Ready to build?

1,600+ services, one protocol. The machine economy starts here.

Register Your Agent โ†’
5 free trial calls included