By the end of this page, GET /weather on your FastAPI or Flask app costs 10,000 microALGO per request, and any x402 client on Algorand can pay it. You use the official x402 Python SDK for the HTTP side, and x402-algorand adds Algorand to it.
This installs the official x402 package (2.28 or later, below 3) and py-algorand-sdk.

FastAPI

The server below is the payee, the fee payer and an in-process facilitator, so the buyer pays exactly the price. It runs on LocalNet, port 9211.
localnet/fastapi_paywall.py
Source: examples/localnet/fastapi_paywall.py

Flask

Flask is synchronous, so it uses the sync classes x402FacilitatorSync and x402ResourceServerSync, and payment_middleware(app, routes, server) from x402.http.middleware.flask, which wraps app.wsgi_app. Same route, port 9212:
localnet/flask_paywall.py
Source: examples/localnet/flask_paywall.py

Test it with a paying client

In a second terminal (drop --url to pay the FastAPI server on 9211):
The network id is your LocalNet’s and differs between machines. The client is explained in Pay from Python; from JavaScript, use x402-avm-js.

What the middleware does

  1. A request to a protected route without payment gets 402 with PAYMENT-REQUIRED; the route does not run.
  2. A request with PAYMENT-SIGNATURE is verified through the facilitator.
  3. If verification succeeds, the route runs.
  4. After the route returns, the middleware settles the payment and adds a PAYMENT-RESPONSE header.

Set the price of a route

The resource server turns each route into payment requirements. The Algorand scheme accepts these price forms:
Register a parser for dollar amounts with ExactAvmServerScheme().register_money_parser(parser); see the reference. To take USDC, the receiving account must opt in. When it builds requirements, the Algorand scheme’s enhance_payment_requirements adds:
  • extra.decimals: 6, unless the route set it.
  • extra.feePayer: a fee payer address of the facilitator. If its signer manages several addresses, one is picked at random, which spreads fee costs. Without a fee payer, the client pays its own fee.
  • extra.genesisHash and extra.genesisId, when the network is registered.

The parts and where they come from

x402ResourceServer also accepts a client for a remote facilitator; see the upstream x402 documentation and Run a facilitator. The facilitator’s signer is covered there too. The upstream SDK also ships EVM and SVM schemes; x402-algorand adds the AVM. It is derived from GoPlausible’s x402-avm 2.0.2 (Apache-2.0) and ships a NOTICE file that reproduces the upstream notices and lists the changed files. Licence: Apache License 2.0.

Next