CR

create-python-x402-server

Automates the setup of x402 payment middleware to protect Python API endpoints with USDC.

Install

mkdir -p .claude/skills/create-python-x402-server && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/15101" && unzip -o skill.zip -d .claude/skills/create-python-x402-server && rm skill.zip

Installs to .claude/skills/create-python-x402-server

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Create x402 payment-protected servers with FastAPI (async) or Flask (sync) for Algorand. Use when building resource servers that require USDC payments, setting up payment middleware, configuring route pricing, or protecting API endpoints with x402. Strong triggers include "create a FastAPI server with x402 payments", "add payment middleware to Flask", "protect my API endpoint with Algorand USDC", "set up x402 resource server in Python", "PaymentMiddlewareASGI setup", "Flask PaymentMiddleware", "how do I accept Algorand payments on my API?", "multi-network payment server", "x402 route configuration".
606 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • Create FastAPI servers with x402 payment protection
  • Create Flask servers with x402 payment protection
  • Configure payment middleware to intercept and verify requests
  • Define route configurations with specific payment requirements
  • Apply payment middleware to FastAPI applications
  • Apply payment middleware to Flask applications

How it works

The skill describes how to build FastAPI or Flask servers that use x402 middleware to intercept requests, check for payment headers, verify payments via a facilitator, and settle payments for protected API endpoints.

Inputs & outputs

You give it
HTTP requests to API endpoints, route configurations, payment options
You get back
Payment-protected API endpoints, 402 Payment Required responses, verified payments, settled payments

When to use create-python-x402-server

  • Protecting API endpoints with USDC payments
  • Setting up x402 payment middleware
  • Configuring route pricing for Python services

About this skill

Creating x402 Payment-Protected Servers in Python

Build FastAPI (async) or Flask (sync) servers that protect API endpoints behind Algorand USDC payments using x402 middleware.

Prerequisites

Before using this skill, ensure:

  1. Python 3.10+ is installed
  2. An Algorand address to receive payments (the payTo address)
  3. A facilitator URL -- use https://x402.org/facilitator or run your own
  4. Understanding of FastAPI or Flask basics

Core Workflow: Middleware-Based Payment Protection

The middleware intercepts requests to protected routes, checks for payment headers, verifies payments through the facilitator, and settles on success.

Client Request
      |
      v
x402 Middleware (checks route config)
      |
      +-- Not protected -> Pass through to handler
      |
      +-- Protected, no payment -> Return 402 with PaymentRequirements
      |
      +-- Protected, has payment -> Verify via Facilitator
            |
            +-- Invalid -> Return 402
            |
            +-- Valid -> Call handler, then settle payment

How to Proceed

Step 1: Install Dependencies

For FastAPI (async):

pip install "x402-avm[fastapi,avm]"

For Flask (sync):

pip install "x402-avm[flask,avm]"

Step 2: Choose Your Framework Pattern

FastAPI uses async components:

  • x402ResourceServer (async)
  • HTTPFacilitatorClient (async)
  • PaymentMiddlewareASGI or payment_middleware

Flask uses sync components:

  • x402ResourceServerSync (sync)
  • HTTPFacilitatorClientSync (sync)
  • PaymentMiddleware or payment_middleware

Step 3: Set Up the Resource Server

Create a facilitator client, resource server, and register the AVM scheme:

FastAPI:

from x402.server import x402ResourceServer
from x402.http import HTTPFacilitatorClient, FacilitatorConfig
from x402.mechanisms.avm.exact import ExactAvmServerScheme

facilitator = HTTPFacilitatorClient(FacilitatorConfig(url="https://x402.org/facilitator"))
server = x402ResourceServer(facilitator)
server.register("algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=", ExactAvmServerScheme())

Flask:

from x402.server import x402ResourceServerSync
from x402.http import HTTPFacilitatorClientSync, FacilitatorConfig
from x402.mechanisms.avm.exact import ExactAvmServerScheme

facilitator = HTTPFacilitatorClientSync(FacilitatorConfig(url="https://x402.org/facilitator"))
server = x402ResourceServerSync(facilitator)
server.register("algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=", ExactAvmServerScheme())

Step 4: Define Route Configurations

Routes map HTTP method + path patterns to payment requirements:

from x402.http import PaymentOption
from x402.http.types import RouteConfig

routes = {
    "GET /api/weather": RouteConfig(
        accepts=PaymentOption(
            scheme="exact",
            network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",
            pay_to="YOUR_ALGORAND_ADDRESS",
            price="$0.01",
        ),
    ),
}

Step 5: Apply Middleware

FastAPI -- Option A (ASGI class, recommended):

from x402.http.middleware.fastapi import PaymentMiddlewareASGI
app.add_middleware(PaymentMiddlewareASGI, routes=routes, server=server)

FastAPI -- Option B (function-based):

from x402.http.middleware.fastapi import payment_middleware
x402_mw = payment_middleware(routes=routes, server=server)

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

Flask:

from x402.http.middleware.flask import PaymentMiddleware
PaymentMiddleware(app, routes, server)

Step 6: Define Route Handlers

Routes listed in the configuration require payment. Unlisted routes pass through freely.

FastAPI:

@app.get("/api/weather")
async def get_weather():
    return {"temperature": 72, "unit": "F"}

Flask:

@app.route("/api/weather")
def get_weather():
    return {"temperature": 72, "unit": "F"}

Important Rules / Guidelines

  1. Match async/sync variants -- FastAPI uses x402ResourceServer + HTTPFacilitatorClient, Flask uses x402ResourceServerSync + HTTPFacilitatorClientSync
  2. Route format -- Keys must be "METHOD /path" (e.g., "GET /api/weather", "POST /api/generate/*")
  3. Wildcard paths -- Use /* suffix to match all sub-paths (e.g., "GET /api/premium/*")
  4. Unlisted routes pass through -- Only routes in the config require payment
  5. Register scheme before middleware -- Call server.register(...) before adding middleware
  6. Price format -- Use "$0.01" for auto-conversion or AssetAmount(amount="10000", asset="10458941") for explicit control
  7. CAIP-2 network IDs -- Use full CAIP-2 identifiers like "algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="

Pricing Options

Simple String Price

PaymentOption(
    scheme="exact",
    network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",
    pay_to="YOUR_ADDRESS",
    price="$0.01",  # Auto-converts to 10000 microUSDC
)

Explicit AssetAmount

from x402.schemas import AssetAmount

PaymentOption(
    scheme="exact",
    network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",
    pay_to="YOUR_ADDRESS",
    price=AssetAmount(
        amount="50000",       # 50000 microUSDC = $0.05
        asset="10458941",     # USDC ASA ID on testnet
        extra={"name": "USDC", "decimals": 6},
    ),
)

Multi-Network (AVM + EVM + SVM)

routes = {
    "GET /api/data/*": RouteConfig(
        accepts=[
            PaymentOption(scheme="exact", pay_to=AVM_ADDRESS, price="$0.01",
                         network="algorand:SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="),
            PaymentOption(scheme="exact", pay_to=EVM_ADDRESS, price="$0.01",
                         network="eip155:84532"),
            PaymentOption(scheme="exact", pay_to=SVM_ADDRESS, price="$0.01",
                         network="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"),
        ],
    ),
}

Common Errors / Troubleshooting

ErrorCauseSolution
TypeError: async errors in FlaskUsing async variants with FlaskUse x402ResourceServerSync and HTTPFacilitatorClientSync
402 returned to all requestsMiddleware applied but facilitator unreachableCheck FACILITATOR_URL and network connectivity
Route not protectedPath pattern mismatchVerify route key format matches: "GET /exact/path" or "GET /prefix/*"
Settlement failsFacilitator cannot reach Algorand networkCheck facilitator logs and algod endpoint
ImportError on middlewareMissing extraspip install "x402-avm[fastapi,avm]" or "x402-avm[flask,avm]"

References / Further Reading

When not to use it

  • When Python 3.10+ is not installed
  • When an Algorand address to receive payments is not available
  • When a facilitator URL is not provided

Prerequisites

Python 3.10+An Algorand addressA facilitator URL

Limitations

  • Requires Python 3.10+ to be installed
  • Requires an Algorand address for payment reception
  • Requires a facilitator URL for payment verification

How it compares

This skill provides a specific implementation guide for integrating x402 payment protection into Python web frameworks, offering concrete steps and code examples for a pay-per-use API model, unlike general web development tutorials.

Compared to similar skills

create-python-x402-server side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
create-python-x402-server (this skill)04moReviewAdvanced
fastapi-templates5202moNo flagsIntermediate
fastapi-pro794moNo flagsAdvanced
fastapi-router-py51moNo flagsBeginner

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

5201,086

fastapi-pro

sickn33

Build high-performance async APIs with FastAPI, SQLAlchemy 2.0, and Pydantic V2. Master microservices, WebSockets, and modern Python async patterns. Use PROACTIVELY for FastAPI development, async optimization, or API architecture.

79181

fastapi-router-py

microsoft

Create FastAPI routers with CRUD operations, authentication dependencies, and proper response models. Use when building REST API endpoints, creating new routes, implementing CRUD operations, or adding authenticated endpoints in FastAPI applications.

525

pydantic-models-py

microsoft

Create Pydantic models following the multi-model pattern with Base, Create, Update, Response, and InDB variants. Use when defining API request/response schemas, database models, or data validation in Python applications using Pydantic v2.

325

backend-architect

sickn33

Expert backend architect specializing in scalable API design, microservices architecture, and distributed systems. Masters REST/GraphQL/gRPC APIs, event-driven architectures, service mesh patterns, and modern backend frameworks. Handles service boundary definition, inter-service communication, resilience patterns, and observability. Use PROACTIVELY when creating new backend services or APIs.

1014

supabase-python

alinaqi

FastAPI with Supabase and SQLAlchemy/SQLModel

05

Search skills

Search the agent skills registry