Blog ·

Store a file for a cent from Python. No account.

A Python program with a USDC wallet stores, finds, reads and deletes a file over a REST API, paying per request with x402. The whole run cost $0.035.

What this is

At the end of this guide you have one Python file, under 300 lines, that stores a file on Artefaktum, finds it by search, downloads it, checks the bytes and deletes it. There is no account and no API key: a wallet pays for each request. Our run of the whole walk-through cost $0.035, and the upload was one cent of that. The same guide exists in TypeScript.

The payments run over x402, an open protocol built on the HTTP status 402 Payment Required: the server answers a request with a price, and the client repeats the request with a signed payment. The money is USDC, a token that tracks the US dollar, on Base, a low-fee network built on Ethereum. You write none of the protocol yourself. The official x402 package wraps httpx, and you call plain REST URLs, so what you learn here carries over to other APIs that speak x402.

These are the prices:

Operation Price Buys
Read: list, get, download $0.005 One request
Search $0.01 One request
Upload up to 10 MiB $0.01 30 days of storage
Upload up to 100 MiB $0.05 30 days of storage
Upload up to 1 GiB $0.50 30 days of storage
New version The upload band of its size At least 30 days from that upload
Extend The band of everything the artifact holds 30 more days
Complete an upload, delete Free A wallet signature, no payment

A band is a size tier: an upload costs the price of the smallest tier its size fits in.

The guide is written for a developer who is at home in Python, has never used x402 and may never have held any crypto.

What you need

Python 3.11 or newer, and the official x402 client:

pip install "x402[httpx,evm,extensions]==2.28.0" httpx==0.28.1 eth-account==0.14.0

The three extras are httpx (the HTTP client the package wraps), evm (signing for Base) and extensions (the sign-in that the free calls use). Keep extensions: without it the two free calls in this guide fail. httpx and eth-account are pinned as well, to the versions the program was checked with.

A wallet private key that holds a few cents of USDC on Base. Create a new wallet in any wallet app that supports Base and export its private key. Send it a dollar of USDC from an exchange or from another wallet, and choose Base as the network when you send. The wallet needs no ETH for fees: a payment here is an authorization that you sign, and the wallet sends no transaction itself. A facilitator, a service that checks the signed payment and submits it to the network, does that part. Artefaktum uses Coinbase’s.

Use a throwaway wallet that holds only what you are ready to spend. The key sits in an environment variable, and whoever has the key can spend everything in the wallet. Never use the key of a wallet that holds real savings, and do not put the key in a file you commit.

export WALLET_KEY=0x...   # the private key, 64 hex characters

The guide builds one file, pay.py, block by block. Paste the blocks in the order they appear and run the file once, at the end. The output under each step is from our own run against production on Base mainnet on 15 November 2026, with the transaction hashes, the ids and the wallet address shortened.

The file starts with the imports and two constants:

import asyncio
import base64
import hashlib
import json
import mimetypes
import os
import re
import sys
import tempfile
from datetime import UTC, datetime
from pathlib import Path

import httpx
from eth_account import Account
from x402 import x402Client
from x402.extensions.sign_in_with_x import (
    CreateSIWxClientExtensionOptions,
    create_siwx_client_extension,
)
from x402.http.clients.httpx import wrapHttpxWithPayment
from x402.mechanisms.evm.exact.register import register_exact_evm_client
from x402.mechanisms.evm.signers import EthAccountSigner

BASE = os.environ.get("ARTEFAKTUM_BASE", "https://api.artefaktum.dev")
NETWORK = "eip155:8453"  # Base mainnet

See the price

A request without a payment costs nothing and tells you the price. Three small helpers come first. x402 headers are JSON, base64-encoded, and an amount is a whole number of millionths of a USDC.

def decode(header):
    """x402 headers are JSON, base64-encoded."""
    return json.loads(base64.b64decode(header))


def usdc(amount):
    """USDC has six decimals: an amount of 5000 is 0.005 USDC."""
    return f"{int(amount) / 1_000_000:g}"


def price_text(amount):
    """What a payment cost, in words. Unknown when the client did not tell us the amount."""
    return f"{usdc(amount)} USDC" if amount else "unknown"

Now ask for your list of projects with plain httpx, no wallet involved:

def see_price():
    """Ask without paying. The answer is 402, and its PAYMENT-REQUIRED header has the price."""
    response = httpx.get(f"{BASE}/v1/projects")
    print(f"GET /v1/projects → {response.status_code}")
    header = response.headers.get("PAYMENT-REQUIRED")
    if response.status_code != 402 or not header:
        raise RuntimeError(f"{BASE} did not answer 402 with a PAYMENT-REQUIRED header")
    offer = decode(header)["accepts"][0]
    print(json.dumps(offer, indent=2))
    print(f"price: {usdc(offer['amount'])} USDC on {offer['network']}")
== See the price ==
GET /v1/projects → 402
{
  "scheme": "exact",
  "network": "eip155:8453",
  "amount": "5000",
  "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  "payTo": "0xeccc9f03eb79c6a5b0fbd919f95656557e6a6173",
  "maxTimeoutSeconds": 60,
  "extra": {
    "name": "USD Coin",
    "version": "2"
  }
}
price: 0.005 USDC on eip155:8453

The status is 402, and the PAYMENT-REQUIRED header carries an offer. Four of its fields matter here:

  • amount is the price in the smallest unit of the token. USDC has six decimals, so "5000" is $0.005.
  • network is where the payment happens. eip155:8453 is Base mainnet.
  • asset is the contract address of the token, here USDC on Base.
  • payTo is the address that receives the money, here Artefaktum’s.

Pay

To pay, the program needs your key. wallet() reads it from WALLET_KEY and stops with a usage line when it is not 64 hex characters. The program never prints the key.

def wallet():
    """The account of the private key in WALLET_KEY: 64 hex characters, 0x in front or not."""
    key = os.environ.get("WALLET_KEY", "").removeprefix("0x")
    if re.fullmatch("[0-9a-fA-F]{64}", key):
        try:
            return Account.from_key("0x" + key)
        except Exception:
            pass  # 64 hex characters, but not a key. The library's message would show them.
    print(
        "usage: WALLET_KEY=0x<private key, 64 hex characters> python pay.py [file]",
        file=sys.stderr,
    )
    sys.exit(2)

make_client() builds the client that pays. It registers two abilities: paying a price in USDC on Base, and signing in, which the free calls need later. Then it wraps httpx. From here on the client answers a 402 that names a price for you: it signs a payment for that price and repeats the request. Only a payment that the server refuses still comes back to your code as a 402.

The client pays whatever price the server quotes, which here is at most the price table above, so keep only small change in the wallet (that is the second reason for a throwaway wallet), especially before you point the same code at another API.

def make_client():
    """An httpx client that answers a 402 by itself: it pays, or signs in, and repeats the call."""
    account = wallet()
    print(f"wallet: {account.address}")

    client = x402Client()
    # Paid routes: sign a USDC payment for the price the server names.
    register_exact_evm_client(client, EthAccountSigner(account), networks=NETWORK)
    # Free routes (complete, delete): sign a message that proves who we are. No money moves.
    client.register_extension(
        create_siwx_client_extension(CreateSIWxClientExtensionOptions(signers=[account]))
    )
    client.on_after_payment_creation(remember_price)

    # Settling a payment on Base takes a few seconds, so allow more than httpx's default 5.
    return wrapHttpxWithPayment(client, base_url=BASE, timeout=60)


def remember_price(context):
    """Called each time the client signs a payment: keep the amount for the cost table."""
    global last_price
    last_price = context.selected_requirements.amount

The program keeps four names at module level: the client that pays, the wallet’s project, the amount of the last payment and the list of what each call cost.

http: httpx.AsyncClient  # the client that pays; main() sets it
project_id: str  # the wallet's project; main() sets it
last_price = None  # the amount of the payment the client signed last
costs = []  # one (call, amount, transaction) row per call, for the table at the end

Every API call goes through one function. It prints the status. A call that was paid for comes back with a PAYMENT-RESPONSE header, the receipt, and then the line also shows the amount and the hash of the transaction that moved the money.

async def call(method, path, body=None):
    """Make one API call, print its result and its price, and return the JSON answer."""
    global last_price
    last_price = None
    response = await http.request(method, path, json=body)
    line = f"{method} {path} → {response.status_code}"
    if response.is_error:
        print(line)
        raise RuntimeError(f"{method} {path} answered {response.status_code}: {response.text}")

    # A call that was paid for comes back with a PAYMENT-RESPONSE header: the receipt.
    receipt = response.headers.get("PAYMENT-RESPONSE")
    if receipt:
        transaction = decode(receipt)["transaction"]
        line += f"  paid {price_text(last_price)} tx {transaction}"
        costs.append((f"{method} {path}", last_price, transaction))
    else:
        costs.append((f"{method} {path}", None, ""))
    print(line)
    return response.json() if response.content else None

The first paid call, made from main() further down, is the same request as before:

== Pay ==
wallet: 0xC89C…c7cf
GET /v1/projects → 200  paid 0.005 USDC tx 0xdc2b…cb5c

This time the answer is 200 with the list of projects. There was no sign-up: a wallet’s first payment creates its account and a default project, and the program keeps that project’s id. The wallet is the account. Settling a payment on Base takes a moment, which is why the client waits up to 60 seconds and not the 5 that httpx allows by default.

Store a file

The program stores the file you name on the command line, or a small text file that it writes itself. It reads the bytes before the first paid call, so a path that cannot be read costs nothing.

def read_file(path):
    """The file's bytes. Read before anything is paid, so a bad path costs nothing."""
    try:
        return path.read_bytes()
    except OSError as error:
        print(f"cannot read {path}: {error.strerror}", file=sys.stderr)
        sys.exit(2)
def sample_file():
    """A small text file to store when the program is run without one."""
    path = Path(tempfile.gettempdir()) / "hello-x402.txt"
    path.write_text(f"Stored over x402 at {datetime.now(UTC).isoformat()}\n")
    return path

Storing takes three steps. Of the three, only the first costs money; checking afterwards that the file is ready costs a read per look.

Reserve. POST /v1/artifacts/uploads says what is coming: a name, a content type and a size. The price follows the size, and up to 10 MiB it is $0.01. The answer has the ids of the new artifact and its version, and a signed upload URL.

async def reserve_upload(filename, data):
    """Reserve room for the file (paid). The answer has the new artifact's ids and an upload URL."""
    return await call(
        "POST",
        "/v1/artifacts/uploads",
        {
            "project_id": project_id,
            "filename": filename,
            "content_type": mimetypes.guess_type(filename)[0] or "application/octet-stream",
            "size_bytes": len(data),
            "title": filename,
            "tags": ["x402-guide"],
        },
    )

Send the bytes. They go straight to storage with a plain HTTP PUT to the signed URL. No wallet is involved and nothing is paid.

Complete. This call tells the server that the bytes are in place. It is free, but the server still has to know that the caller is the wallet that paid for the reservation. With no account and no API key, the proof is a signature. The route answers 402 with a challenge from sign-in-with-x, the x402 extension for proving which wallet you are, in place of a price. The client signs that one-time message with the wallet key and repeats the call. No money moves, so the line in the output has no paid part. The program sends the file’s sha256 with this call, to have something to compare the download with.

After that the server checks the stored bytes in the background, and the program asks for the artifact until its status is ready. Each look is a paid read at $0.005. The looks are 4 seconds apart and there are at most 10. In our run the file was ready on the first look.

async def store_file(data, reserved):
    """Send the bytes to storage (free), complete the upload (free), wait until it is ready."""
    artifact_id = reserved["artifact"]["id"]
    version_id = reserved["artifact"]["version_id"]

    # The bytes go straight to storage, to a signed URL. No wallet is involved.
    upload = reserved["upload"]
    put = httpx.put(upload["url"], content=data, headers=upload["headers"])
    print(f"PUT the bytes to storage → {put.status_code}")
    if put.is_error:
        raise RuntimeError(f"storage refused the bytes: {put.status_code} {put.text}")

    # Completing is free: the server asks only for proof that we are the wallet that paid.
    # We send the file's sha256 with it, to compare with what we download later.
    await call(
        "POST",
        f"/v1/artifacts/{artifact_id}/versions/{version_id}/complete",
        {"sha256": hashlib.sha256(data).hexdigest()},
    )

    # The server checks the stored bytes in the background. Each look is a paid read.
    for look in range(1, 11):
        await asyncio.sleep(4)
        artifact = await call("GET", f"/v1/artifacts/{artifact_id}")
        if artifact["status"] == "ready":
            return
        print(f"status is {artifact['status']} (look {look} of 10, each look is paid)")
    raise RuntimeError("the artifact is not ready after 10 looks")
== Store a file ==
POST /v1/artifacts/uploads → 201  paid 0.01 USDC tx 0xd247…c8af
PUT the bytes to storage → 200
POST /v1/artifacts/01a1e045-…/versions/01a1e045-…/complete → 200
GET /v1/artifacts/01a1e045-… → 200  paid 0.005 USDC tx 0xf10b…6e49

The file is stored. The reservation cost one cent, and the look that found it ready cost half a cent.

Find it and read it back

A search costs $0.01. The program searches the wallet’s project for the file’s name, picks its own artifact out of the results and takes the sha256 that the server holds for it. The download call costs $0.005 and returns a signed URL, not the bytes. Fetching that URL is a plain GET, free, with no wallet involved. The program hashes what it gets and compares.

async def find_and_read(artifact_id, query):
    """Search for the artifact (paid), download it (paid) and check the bytes."""
    found = await call(
        "POST",
        "/v1/artifacts/search",
        {"project_id": project_id, "query": query, "mode": "text", "limit": 5},
    )
    hits = [hit["artifact"] for hit in found["items"] if hit["artifact"]["id"] == artifact_id]
    if not hits:
        raise RuntimeError(f"search for {query!r} did not find {artifact_id}")
    expected = hits[0]["latest_version"]["sha256"]

    # The download call returns a signed URL, not the bytes. Fetching that URL is free.
    download = await call("GET", f"/v1/artifacts/{artifact_id}/download")
    stored = httpx.get(download["url"])
    print(f"GET the bytes from storage → {stored.status_code}")
    if stored.is_error:
        raise RuntimeError(f"storage refused the download: {stored.status_code} {stored.text}")
    actual = hashlib.sha256(stored.content).hexdigest()
    if actual != expected:
        raise RuntimeError(f"sha256 differs: stored {expected}, downloaded {actual}")
    print(f"downloaded {len(stored.content)} bytes, sha256 matches")
== Find it and read it back ==
POST /v1/artifacts/search → 200  paid 0.01 USDC tx 0x0c42…bf3b
GET /v1/artifacts/01a1e045-…/download → 200  paid 0.005 USDC tx 0x572d…b4d0
GET the bytes from storage → 200
downloaded 53 bytes, sha256 matches

The 53 bytes are the small text file the program wrote for itself.

Delete it

Deleting is free for the same reason completing is: the server needs to know that you own the artifact, and a signature from the wallet proves it.

async def delete(artifact_id):
    """Delete the artifact. Free: like complete, it needs a signature, not a payment."""
    await call("DELETE", f"/v1/artifacts/{artifact_id}")
== Delete it ==
DELETE /v1/artifacts/01a1e045-… → 202

main() ties the steps together. The delete sits in a finally: from the reservation on there is something to delete, whatever goes wrong after it. If the delete itself fails, the program says so and exits with status 1.

async def main():
    global http, project_id
    # Check the key and read the file first: a mistake here should cost nothing.
    wallet()
    path = Path(sys.argv[1]) if len(sys.argv) > 1 else sample_file()
    data = read_file(path)
    deleted = True

    print("== See the price ==")
    see_price()

    print("\n== Pay ==")
    async with make_client() as http:
        try:
            # A wallet's first payment creates its account and a default project.
            projects = await call("GET", "/v1/projects")
            project_id = projects["items"][0]["id"]

            print("\n== Store a file ==")
            reserved = await reserve_upload(path.name, data)
            artifact_id = reserved["artifact"]["id"]
            try:
                await store_file(data, reserved)
                print("\n== Find it and read it back ==")
                await find_and_read(artifact_id, path.name)
            finally:
                # From the reservation on there is something to delete, whatever went wrong.
                print("\n== Delete it ==")
                try:
                    await delete(artifact_id)
                except Exception as error:
                    deleted = False
                    print(f"could not delete {artifact_id}: {error}", file=sys.stderr)
                    print("it expires on its own after 30 days", file=sys.stderr)
        finally:
            print("\n== What it cost ==")
            print_costs()
    if not deleted:
        sys.exit(1)

If you do not delete, nothing bad happens. An upload buys 30 days of storage. The artifact expires at the end of them and is removed, unless you extend it first: POST /v1/artifacts/{id}/extend buys 30 more days at the band of everything the artifact holds, which for a small file is the same cent again.

What it cost

The last function prints the calls the run made, the price of each and the transaction that paid for it. The table lists the calls that succeeded; a call that fails is not in it.

def print_costs():
    """The calls this run made, what each one cost, and the transaction that paid for it."""
    width = max([len(name) for name, _, _ in costs], default=4)
    print(f"{'call'.ljust(width)} | price      | tx")
    for name, amount, transaction in costs:
        price = price_text(amount) if transaction else "free"
        print(f"{name.ljust(width)} | {price.ljust(10)} | {transaction}")
    paid = [amount for _, amount, transaction in costs if transaction]
    total = sum(int(amount) for amount in paid if amount)
    print(f"total: {usdc(total)} USDC in {len(paid)} payments")
    if None in paid:
        print("the total leaves out the payments whose amount is unknown")

Five more lines start the program, and the file is complete:

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as error:
        sys.exit(f"failed: {error}")
python pay.py              # stores a small text file it writes itself
python pay.py report.pdf   # or a file of yours

This is the table our run ended with:

== What it cost ==
call                                                       | price      | tx
GET /v1/projects                                           | 0.005 USDC | 0xdc2b…cb5c
POST /v1/artifacts/uploads                                 | 0.01 USDC  | 0xd247…c8af
POST /v1/artifacts/01a1e045-…/versions/01a1e045-…/complete | free       |
GET /v1/artifacts/01a1e045-…                               | 0.005 USDC | 0xf10b…6e49
POST /v1/artifacts/search                                  | 0.01 USDC  | 0x0c42…bf3b
GET /v1/artifacts/01a1e045-…/download                      | 0.005 USDC | 0x572d…b4d0
DELETE /v1/artifacts/01a1e045-…                            | free       |
total: 0.035 USDC in 5 payments

Five payments, 0.035 USDC in total: one cent for the upload, one cent for the search and three reads at half a cent each: the list of projects, the look that found the file ready and the download. Completing and deleting cost nothing. Had the file needed more looks before it was ready, each one would have added $0.005.

Rules worth knowing

  • An API key and a wallet never stack. A request with an Authorization header takes the API-key path and is never asked to pay; a payment header on it is ignored. Only a request without that header gets the 402.
  • A call the server rejects is not charged. The server settles your payment only after the request has done its work. When the request ends in an error before that, a 404 or a validation error for example, the payment is voided and nothing is charged. In the rare case that a call ends in an error after the payment was submitted, a 502 for example, the transfer may still have gone through. The transaction is then visible on a block explorer, and a payment taken for a request that was not served is refunded in USDC to the address that paid it: email support@artefaktum.dev with the transaction hash. The refund policy has the wording.
  • A payment fits one price. A signed payment whose amount differs from the price the server quotes is refused with 402 and the error invalid_payment_requirements. One that was used before is refused with payment_already_used. The client signs a new payment for every call, so you meet these only when you build payments by hand.
  • An empty wallet gets the 402 again. The error field of the decoded PAYMENT-REQUIRED header then carries the facilitator’s reason, and that reason can be vague. When we probed Coinbase’s facilitator with a wallet that held nothing, it answered invalid_payload, not a word about the balance. If a paid call is refused, look at the wallet’s USDC balance on Base first.
  • 503 payments_busy means try again. The server settles only a few payments at once. Beyond that it answers 503 with the code payments_busy and Retry-After: 1. Nothing was charged.
  • Your payments are public. Any Base block explorer, basescan.org for one, shows them on the page of your wallet address. Look under its token transfers, not in its list of transactions: the facilitator submits the transaction, not your wallet. Each payment is a USDC transfer from your wallet to the payTo address of the offer.

Where next

  • Pay per request: the prices, the protocol and what 30 days of storage means.
  • The REST reference: the routes and their fields.
  • https://api.artefaktum.dev/.well-known/x402: the machine-readable manifest of the paid routes and their prices.
  • The complete program is the sum of the blocks above, in the order they appear.
  • The same guide in TypeScript.

This page as Markdown: /blog/pay-per-request-from-python.md