0% fee SWIFT with a U.S. BIC for Physical Goods TradersApply now
← All articles
Developers8 min read

Add x402 payments to FastAPI with HEVN

Turn an existing FastAPI endpoint into a paid USDC resource. The x402 Python SDK handles the challenge and settlement flow; your HEVN Base deposit address receives the proceeds.

This tutorial uses FastAPI + the official x402 Python v2 SDK + CDP's hosted facilitator. HEVN is the recipient wallet, not a facilitator. The implementation below is a Base mainnet example: a real successful payment moves real USDC. Use a separate testnet address and eip155:84532 for sandbox experiments, not your HEVN deposit address.

1. Find your HEVN address for USDC on Base

Sign in to HEVN and open Account → Deposit → Crypto → Direct, at /account/deposit/crypto?tab=direct. Select USDC, then the Base blockchain. Copy the displayed deposit address and confirm that the selected asset and network still read USDC / Base. Use that address only for the supported deposit combination; never paste a Base Sepolia, Ethereum, or other-network address into this production configuration. If the address is not available for your account, ask HEVN before proceeding.

You will pass this public address as pay_to. No HEVN private key or HEVN API key belongs in the FastAPI application.

2. Install the existing libraries

In your Python project, install the framework, x402 FastAPI/EVM extras, the CDP SDK for the hosted facilitator, and an ASGI runner:

python -m pip install 'fastapi' 'uvicorn' 'x402[fastapi,evm]>=2,<3' 'cdp-sdk'

The x402 v1 import x402.fastapi.middleware.require_payment belongs to the deprecated legacy package. For v2, use x402.http.middleware.fastapi.PaymentMiddlewareASGI. Pin exact tested versions in your application's lockfile before production deployment.

Create a CDP API key with access to its x402 facilitator and configure these environment variables in your secret manager (never commit the actual values):

export HEVN_BASE_USDC_ADDRESS='0xYourHevnBaseUsdcDepositAddress'
export CDP_API_KEY_ID='your-cdp-key-id'
export CDP_API_KEY_SECRET='your-cdp-key-secret'

The CDP key is for facilitator authentication. It is not a destination wallet; settlement uses HEVN_BASE_USDC_ADDRESS below. You do not need a CDP wallet secret to receive into your existing HEVN address.

3. Wrap a FastAPI route with x402

Create main.py (or adapt the route and middleware into your current application):

import os
import re

from cdp.x402 import create_facilitator_config
from fastapi import FastAPI
from x402.http import HTTPFacilitatorClient, PaymentOption
from x402.http.middleware.fastapi import PaymentMiddlewareASGI
from x402.http.types import RouteConfig
from x402.mechanisms.evm.exact import ExactEvmServerScheme
from x402.server import x402ResourceServer

receiver = os.environ["HEVN_BASE_USDC_ADDRESS"]
if not re.fullmatch(r"0x[a-fA-F0-9]{40}", receiver):
    raise ValueError("Set a valid HEVN USDC deposit address for Base")

network = "eip155:8453"
facilitator = HTTPFacilitatorClient(create_facilitator_config())
server = x402ResourceServer(facilitator)
server.register(network, ExactEvmServerScheme())

routes = {
    "GET /report": RouteConfig(
        accepts=[
            PaymentOption(
                scheme="exact",
                price="$0.01",
                network=network,
                pay_to=receiver,
            ),
        ],
        description="One paid report",
        mime_type="application/json",
    ),
}

app = FastAPI()
app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server)


@app.get("/health")
async def health():
    return {"status": "ok"}


@app.get("/report")
async def report():
    return {"report": "Your paid report goes here"}

The GET /report key must match the HTTP method and path of your actual route. /health stays free because it is not in routes. The middleware issues the 402 challenge, asks the facilitator to verify and settle the payment, and controls access to the handler. You do not need to implement a raw 402 response or decode a signed payment yourself.

4. Run and inspect the challenge

uvicorn main:app --port 8000
curl -i http://127.0.0.1:8000/health
curl -i http://127.0.0.1:8000/report

The health route should return 200; the unpaid report should return 402 Payment Required with the PAYMENT-REQUIRED header. This checks the payment gate, not settlement or a live deposit. If the challenge advertises the wrong payTo or network, stop before testing with real funds and check the configuration.

5. Make one real paid request

Use an x402-compatible paying client, funded with a small amount of real USDC on Base mainnet, to call /report. The client handles the 402 challenge and sends a signed PAYMENT-SIGNATURE on retry. Do not send USDC directly to the endpoint as a manual transfer: the middleware needs the x402 authorization and settlement flow.

Check for a successful response and its PAYMENT-RESPONSE receipt; verify the transaction on Base and confirm that the deposit appears in HEVN. Keep the transaction hash, route, amount, payer information available to you, and corresponding sale or invoice for reconciliation. If the facilitator rejects the payment, verify its Base-mainnet and USDC support and the CDP credentials; never switch to the public testnet facilitator while leaving a HEVN mainnet receiver in place.

For multiple paid resources, add another "METHOD /path" entry with its own price and description. Protect costly computations and side effects against retries, and avoid caching paid responses across customers. Check the official FastAPI example and CDP Python facilitator example when updating packages.

Withdraw your earnings

After a payment settles and the USDC is credited and available in HEVN, you can withdraw through an eligible HEVN route or convert first where supported. Check your account's withdrawal options and applicable fees and compliance requirements. Your x402 facilitator handles verification and settlement; withdrawal is a separate action in HEVN. For another stack, see the JavaScript/Express guide.