> ## Documentation Index
> Fetch the complete documentation index at: https://docs.4mica.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Flask

> Protect Flask routes with 4Mica x402 payment middleware.

# Flask

Use Flask when you want synchronous Python route handlers with 4Mica payment protection. The `4mica-x402` Flask middleware handles HTTP 402 responses, guarantee verification, and settlement for protected routes.

## Prerequisites

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

## Install

```bash theme={null}
pip install "4mica-x402[flask]" "4mica-x402[requests]"
```

## Create wallet

Create a dedicated EVM wallet for the buyer client and use a seller address for `payTo`. For wallet setup, see [Wallet](/core-concepts/wallet).

```bash theme={null}
PRIVATE_KEY=0xYourPrivateKey
PAY_TO=0xYourSellerAddress
```

<Warning>
  Use the private key only for buyer-side signing. Use `PAY_TO` as the seller
  address advertised by protected routes.
</Warning>

## 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](/core-concepts/deposits-and-withdrawals).

## Protect a route

```python theme={null}
from flask import Flask, jsonify
from fourmica_x402.http import flask_payment_middleware_from_config

app = Flask(__name__)

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

flask_payment_middleware_from_config(
    app,
    routes,
)

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

if __name__ == "__main__":
    app.run(port=5000)
```

## Support payment

Use the synchronous `requests` wrapper in Flask clients, scripts, workers, or any blocking Python code.

```python theme={null}
from x402 import x402ClientSync
from x402.http.clients import x402_requests
from fourmica_x402.client_scheme import FourMicaEvmScheme

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

session = x402_requests(client)
response = session.get("http://localhost:5000/premium-content")
print(response.status_code, response.json())
```

## What happens

1. The buyer requests `/premium-content` without payment.
2. Flask returns HTTP 402 with payment requirements.
3. The `requests` 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.
