DEV Community

int dev
int dev

Posted on

Add x402 pay-per-call to a FastAPI server in ~40 lines

Adding x402 pay-per-call to a FastAPI server in ~40 lines

x402 is the Coinbase HTTP-payment standard: your server returns 402 Payment Required with payment terms, the client signs a USDC transfer, retries with the payment header, and your middleware settles on-chain. No API keys, no accounts — the signature IS the auth.

import base64, json
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

PAY_TO = "0xYourWallet"
FACILITATOR = "https://facilitator.payai.network"

def paywall(price_usdc: str, description: str):
    async def mw(request: Request, call_next):
        pay_header = request.headers.get("x-payment")
        if not pay_header:
            # tell the client what to pay
            return JSONResponse({
                "x402Version": 1,
                "accepts": [{
                    "scheme": "exact", "network": "base",
                    "maxAmountRequired": price_usdc,
                    "resource": str(request.url),
                    "payTo": PAY_TO, "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
                    "description": description, "mimeType": "application/json",
                }],
                "error": "Payment required",
            }, status_code=402)
        # verify + settle via facilitator
        import httpx
        payload = json.loads(base64.b64decode(pay_header))
        async with httpx.AsyncClient() as c:
            ok = await c.post(f"{FACILITATOR}/verify",
                json={"x402Version":1,"paymentHeader":pay_header,
                      "paymentRequirements":payload["payload"]["requirements"]})
            if not ok.json()["isValid"]: return JSONResponse({"error":"bad payment"},402)
            resp = await call_next(request)
            await c.post(f"{FACILITATOR}/settle", json={"x402Version":1,"paymentHeader":pay_header,
                      "paymentRequirements":payload["payload"]["requirements"]})
            return resp
    return mw
Enter fullscreen mode Exit fullscreen mode

Wrap any route with it and you sell per-call. That's the whole server side — the client side is x402-fetch or 30 lines with viem for EVM signing.

I run this in production on AtlasData (20+ endpoints, $0.001–$0.50/call): https://atlasdata.shares.zrok.io/llms.txt. AMA about the sharp edges — facilitator quirks, Base USDC specifics, L402 for Lightning.

Top comments (0)