Skip to main content

FastAPI

Use FastAPI when you want async Python route handlers with 4Mica payment protection. The 4mica-x402 FastAPI middleware returns HTTP 402 responses, verifies retried payment headers, settles guarantees, and serves the protected response after payment succeeds.

Prerequisites

  • Python 3.10 or later.
  • A FastAPI app.
  • A seller wallet address for payTo.
  • A buyer wallet with deposited 4Mica collateral for paid requests.

Install

pip install "4mica-x402[fastapi]" "4mica-x402[httpx]"

Create wallet

Create a dedicated EVM wallet for the buyer client and use a seller address for payTo. For wallet setup, see Wallet.
PRIVATE_KEY=0xYourPrivateKey
PAY_TO=0xYourSellerAddress
Use the private key only for buyer-side signing. Use PAY_TO as the seller address advertised by protected routes.

Deposit collateral

Deposit collateral for the buyer wallet before it calls the protected route. Use the same network in the buyer scheme and route configuration. To learn more about collateral setup, see Deposits and Withdrawals.

Protect a route

from fastapi import FastAPI
from fourmica_x402.http import fastapi_payment_middleware_from_config

app = FastAPI()

routes = {
    "GET /premium-content": {
        "accepts": {
            "scheme": "4mica-credit",
            "price": "$0.10",
            "network": "eip155:11155111",
            "payTo": "0xYourAddress",
        },
        "description": "Access to premium FastAPI content",
    },
}

middleware = fastapi_payment_middleware_from_config(
    routes,
)

@app.middleware("http")
async def x402_middleware(request, call_next):
    return await middleware(request, call_next)

@app.get("/premium-content")
async def premium_content():
    return {"message": "This is premium content behind a paywall"}

Support payment

Use the async httpx wrapper in FastAPI clients, background tasks, or other asyncio code.
import httpx
from x402 import x402Client
from x402.http.clients import x402_httpx_transport
from fourmica_x402.client_scheme import FourMicaEvmScheme

client = x402Client()
client.register("eip155:11155111", FourMicaEvmScheme("0xYourPrivateKey"))

async with httpx.AsyncClient(
    transport=x402_httpx_transport(client)
) as session:
    response = await session.get("http://localhost:8000/premium-content")
    print(response.status_code, response.json())

What happens

  1. The buyer requests /premium-content without payment.
  2. FastAPI returns HTTP 402 with payment requirements.
  3. The httpx wrapper creates a unique request ID, signs a guarantee, and retries with a payment header.
  4. The middleware verifies and settles the payment before your handler serves the response.