FastAPI
Use FastAPI when you want async Python route handlers with 4Mica payment protection. The4mica-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
Create wallet
Create a dedicated EVM wallet for the buyer client and use a seller address forpayTo. For wallet setup, see Wallet.
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
Support payment
Use the asynchttpx wrapper in FastAPI clients, background tasks, or other asyncio code.
What happens
- The buyer requests
/premium-contentwithout payment. - FastAPI returns HTTP 402 with payment requirements.
- The
httpxwrapper creates a unique request ID, signs a guarantee, and retries with a payment header. - The middleware verifies and settles the payment before your handler serves the response.