In the previous parts I covered hybrid authentication (API keys for humans, x402 for agents), the FastAPI quirks that appeared when implementing the 402 challenge and payment receipt headers, and the workarounds that made the responses protocol-compliant.
This part is about getting the service live and proving the full flow works.
Quick Recap
- Endpoints can be accessed with a traditional
X-API-Key(checked against PostgreSQL). - If no key is present, the server returns a properly shaped HTTP 402 with the x402 challenge (no
"detail"wrapper). - Agents pay with USDC on Base, send the payment header, and the server verifies + settles via the Coinbase facilitator before returning data.
- On success, a
PAYMENT-RESPONSEheader is attached via middleware.
Now it was time to deploy and test both paths for real.
Deploying to DigitalOcean
I chose a simple Droplet (Ubuntu 24.04, 2 GB RAM) and ran the FastAPI app with Gunicorn + Uvicorn workers behind Nginx.
Key deployment steps:
- Provision the Droplet and point the domain (
api.data4agents.dev) to it. - Install Python, PostgreSQL, Redis, and Nginx.
- Set up a systemd service for the app so it restarts on reboot.
- Use Certbot for HTTPS.
- Load environment variables (database URL, x402 wallet, facilitator keys, etc.) via a
.envfile that is not committed.
Once the service was up, the public base URL became https://api.data4agents.dev.
Testing the API Key Path (Postman)
I created a test subscriber in the database and generated an API key.
In Postman:
- Method:
GET - URL:
https://api.data4agents.dev/v1/prices/realtime - Header:
X-API-Key: <the key I created>
The request returned 200 with the expected JSON payload. No payment challenge was issued. This confirmed the Web2 path still works after deployment.
Testing the x402 Path (Simulated Agent)
To simulate an autonomous agent I wrote a small Python script that fully exercises the 402 → pay → retry loop. It uses requests and eth-account to sign an exact-scheme payment.
import os import json import base64 import time import requests from eth_account import Account from eth_account.messages import encode_typed_data # Configuration API_URL = "https://api.data4agents.dev/v1/prices/realtime" PRIVATE_KEY = os.environ["WALLET_PRIVATE_KEY"] # Never hardcode account = Account.from_key(PRIVATE_KEY) PAYER_ADDRESS = account.address def decode_header_or_body(response): """Prefer PAYMENT-REQUIRED header (v2); fall back to JSON body.""" header = response.headers.get("PAYMENT-REQUIRED") if header: padded = header + "=" * (-len(header) % 4) return json.loads(base64.b64decode(padded)) return response.json() def build_payment_payload(challenge: dict, payer: str) -> dict: """Build a minimal exact-scheme payment payload and sign it.""" accepted = challenge["accepts"][0] # Take the first (and usually only) option now = int(time.time()) authorization = { "from": payer, "to": accepted["payTo"], "value": accepted["amount"], "validAfter": str(now - 10), "validBefore": str(now + int(accepted.get("maxTimeoutSeconds", 60))), "nonce": "0x" + os.urandom(32).hex(), } # EIP-712 typed data for USDC transferWithAuthorization (simplified domain) typed_data = { "types": { "EIP712Domain": [ {"name": "name", "type": "string"}, {"name": "version", "type": "string"}, {"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}, ], "TransferWithAuthorization": [ {"name": "from", "type": "address"}, {"name": "to", "type": "address"}, {"name": "value", "type": "uint256"}, {"name": "validAfter", "type": "uint256"}, {"name": "validBefore", "type": "uint256"}, {"name": "nonce", "type": "bytes32"}, ], }, "domain": { "name": accepted.get("extra", {}).get("name", "USDC"), "version": accepted.get("extra", {}).get("version", "2"), "chainId": int(accepted["network"].split(":")[1]), "verifyingContract": accepted["asset"], }, "primaryType": "TransferWithAuthorization", "message": authorization, } signed = account.sign_message(encode_typed_data(full_message=typed_data)) payload = { "x402Version": challenge.get("x402Version", 2), "resource": challenge.get("resource"), "accepted": accepted, "payload": { "signature": signed.signature.hex(), "authorization": authorization, }, } return payload def main(): print(f"Paying from {PAYER_ADDRESS}") # 1. Initial request (no payment) print("\n--- First request (expect 402) ---") resp = requests.get(API_URL, timeout=15) print(f"Status: {resp.status_code}") if resp.status_code != 402: print("Unexpected status. Response:", resp.text[:500]) return challenge = decode_header_or_body(resp) print("Challenge received:", json.dumps(challenge, indent=2)[:800], "...") # 2. Build and sign payment payment_payload = build_payment_payload(challenge, PAYER_ADDRESS) payment_b64 = base64.b64encode(json.dumps(payment_payload).encode()).decode() # 3. Retry with PAYMENT-SIGNATURE print("\n--- Retry with payment ---") headers = {"PAYMENT-SIGNATURE": payment_b64} resp2 = requests.get(API_URL, headers=headers, timeout=30) print(f"Status: {resp2.status_code}") receipt = resp2.headers.get("PAYMENT-RESPONSE") if receipt: try: padded = receipt + "=" * (-len(receipt) % 4) print("PAYMENT-RESPONSE:", base64.b64decode(padded).decode()[:500]) except Exception: print("PAYMENT-RESPONSE (raw):", receipt[:200]) print("\nBody:", resp2.text[:1000]) if __name__ == "__main__": main() How to run it:
pip install requests eth-account export WALLET_PRIVATE_KEY=0x... python x402_client_test.py On a successful run against the live endpoint:
- The first call returns 402 with a properly shaped challenge.
- The second call (with the signed payload) returns 200 and a
PAYMENT-RESPONSEheader. - Settlement appears on-chain shortly after.
Notes on the script:
- It prefers the
PAYMENT-REQUIREDheader (x402 v2) but falls back to the JSON body. - The EIP-712 signing is a simplified but functional version of the exact scheme. In production agents you would normally use the official
x402Python SDK, which handles domain separators, nonces, and edge cases more robustly. - Always load the private key from an environment variable and never log it.
- The script does not implement spending caps or requirement validation — those are recommended for real agents.
What I Learned
- DigitalOcean Droplets remain a straightforward way to get a FastAPI + Postgres stack live.
- Testing both paths separately is essential. The API-key path is simple; the x402 path needs a real wallet and a working facilitator.
- A small client script that fully exercises the 402 → sign → retry loop made debugging much faster than manual header crafting in Postman.
- Prefer the official x402 SDK for production agents; the manual script above is mainly useful for understanding and testing the handshake.
Next I’ll look at how agents actually discover the endpoints (bazaar / llms.txt) and start measuring real usage.
Have you deployed an x402-protected API? Drop a comment with any surprises you hit during end-to-end testing.