# Copy-paste examples

Copy-paste examples of a paid Munition call: curl, TypeScript with an x402 client, and Python, all for POST /v1/serper/search, a Google search.

Every example makes the same request: a Google web search for "x402 protocol" through `POST https://api.munition.io/v1/serper/search`, paid per call with x402. One search costs 0.004 USDC. The body is the same everywhere:

```json
{ "q": "x402 protocol", "gl": "us", "hl": "en", "num": 10 }
```

`q` is the query (required), `gl` the country, `hl` the interface language, `num` the number of results (1 to 100). The [Web research API](/docs/services/web-research) reference lists every field.

## Before you start

- **A wallet holding USDC** on one of the [accepted networks](/docs/payments/networks). The TypeScript example pays on Base.
- **Keep the private key out of the agent.** Read it from the environment or a secret store, never from a prompt or a source file.
- **One request, one price.** The `402` states the exact amount before anything is signed. Prices are listed on [Prices and price discovery](/docs/payments/prices).
- **Send an `Idempotency-Key`** with the paid request, and keep the same key if you retry that same request. [Errors and refunds](/docs/payments/errors) explains what a retry does.

The five steps behind every example are explained on [Pay per call with x402](/docs/payments/x402).

## curl

curl cannot sign a payment, but it shows the protocol by hand. First, call the endpoint without payment. The API answers `402 Payment Required` and costs nothing:

```bash
curl -sS -i https://api.munition.io/v1/serper/search \
  -H 'Content-Type: application/json' \
  --data '{"q":"x402 protocol","gl":"us","hl":"en","num":10}'
```

The payment requirements are in the `PAYMENT-REQUIRED` response header, as base64-encoded JSON. To read them (requires `jq`):

```bash
curl -sS -o /dev/null -D - https://api.munition.io/v1/serper/search \
  -H 'Content-Type: application/json' \
  --data '{"q":"x402 protocol","gl":"us","hl":"en","num":10}' \
  | grep -i '^payment-required:' | cut -d' ' -f2 | tr -d '\r' | base64 --decode | jq .
```

The decoded JSON is shown and explained in [Reading the 402](/docs/payments/x402#reading-the-402). Sign one entry of its `accepts` list with your wallet's x402 client, base64-encode the resulting payment payload, and send the same request again with it in `PAYMENT-SIGNATURE`:

```bash
curl -sS -i https://api.munition.io/v1/serper/search \
  -H 'Content-Type: application/json' \
  -H "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  -H 'Idempotency-Key: serper-x402-protocol-1' \
  --data '{"q":"x402 protocol","gl":"us","hl":"en","num":10}'
```

A `200` carries the search results in the body and the settlement receipt in the `PAYMENT-RESPONSE` header.

## TypeScript

This example uses the x402 TypeScript SDK (`@x402/core` and `@x402/evm`, the 2.x packages Munition's own server uses) and `viem` for the wallet. It pays in USDC on Base.

```bash
npm install @x402/core @x402/evm viem
```

Save it as `search.mts` (the `.mts` extension makes it an ES module, which top-level `await` needs), set `X402_PRIVATE_KEY` to the private key of a wallet holding USDC on Base, and run it with `npx tsx search.mts` (Node.js 20 or later).

```ts
import { x402Client } from "@x402/core/client";
import { x402HTTPClient } from "@x402/core/http";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const url = "https://api.munition.io/v1/serper/search";
const body = { q: "x402 protocol", gl: "us", hl: "en", num: 10 };

// The agent's wallet: USDC on Base (eip155:8453). Keep the key in the environment.
const account = privateKeyToAccount(process.env.X402_PRIVATE_KEY as `0x${string}`);
const coreClient = new x402Client();
registerExactEvmScheme(coreClient, { signer: account, networks: ["eip155:8453"] });
const client = new x402HTTPClient(coreClient);

// 1. Call the endpoint without payment.
const unpaid = await fetch(url, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify(body),
});
if (unpaid.status !== 402) throw new Error(`Expected 402, got ${unpaid.status}`);

// 2. Read the payment requirements from the PAYMENT-REQUIRED header.
const paymentRequired = client.getPaymentRequiredResponse((name) => unpaid.headers.get(name), await unpaid.json());

// 3. Sign a payment for the Base entry of "accepts" with the wallet.
const paymentPayload = await client.createPaymentPayload(paymentRequired);

// 4. Retry the same request with the PAYMENT-SIGNATURE header.
const paid = await fetch(url, {
  method: "POST",
  headers: {
    "content-type": "application/json",
    "idempotency-key": crypto.randomUUID(),
    ...client.encodePaymentSignatureHeader(paymentPayload),
  },
  body: JSON.stringify(body),
});
if (!paid.ok) throw new Error(`Paid request failed with ${paid.status}: ${await paid.text()}`);

// 5. Get the result, and the settlement receipt from the PAYMENT-RESPONSE header.
const settlement = client.getPaymentSettleResponse((name) => paid.headers.get(name));
const result = await paid.json();
console.log(`Paid on ${settlement.network}, transaction ${settlement.transaction}`);
console.log(result.organic[0]?.link);
```

`registerExactEvmScheme` without `networks` registers every EVM network; the client then signs for the first entry of `accepts` it supports. Naming the network keeps the choice explicit.

## Python

This example uses only the Python standard library for HTTP. Python has no signing step built in, so `sign_payment` marks where your wallet's x402 signing code plugs in: it receives the decoded requirements and returns the payment payload described in [step 3](/docs/payments/x402#3-sign-the-payment-from-your-wallet).

```python
import base64
import json
import urllib.error
import urllib.request
import uuid

URL = "https://api.munition.io/v1/serper/search"
BODY = {"q": "x402 protocol", "gl": "us", "hl": "en", "num": 10}


def post(headers=None):
    request = urllib.request.Request(
        URL,
        data=json.dumps(BODY).encode(),
        headers={"Content-Type": "application/json", **(headers or {})},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            return response.status, response.headers, response.read()
    except urllib.error.HTTPError as error:  # 402 and every other non-2xx status
        return error.code, error.headers, error.read()


def sign_payment(payment_required):
    """Plug your wallet's x402 signing code in here.

    Pick one entry of payment_required["accepts"] that your wallet can pay,
    sign it, and return the x402 version 2 payment payload as a dict:
    {"x402Version": 2, "resource": payment_required["resource"],
     "accepted": <the entry you signed>, "payload": <the signed authorization>}
    """
    raise NotImplementedError("sign the payment with your wallet's x402 code")


# 1. Call the endpoint without payment.
status, headers, body = post()
if status != 402:
    raise SystemExit(f"expected 402, got {status}: {body.decode()}")

# 2. Decode the payment requirements from the PAYMENT-REQUIRED header.
payment_required = json.loads(base64.b64decode(headers["PAYMENT-REQUIRED"]))
for option in payment_required["accepts"]:
    print(option["network"], option["asset"], option["amount"])

# 3. Sign the payment from your wallet.
payment_payload = sign_payment(payment_required)

# 4. Retry the same request with the PAYMENT-SIGNATURE header.
signature = base64.b64encode(json.dumps(payment_payload).encode()).decode()
status, headers, body = post({"PAYMENT-SIGNATURE": signature, "Idempotency-Key": str(uuid.uuid4())})
if status != 200:
    raise SystemExit(f"paid request failed with {status}: {body.decode()}")

# 5. Get the result, and the settlement receipt from the PAYMENT-RESPONSE header.
receipt = json.loads(base64.b64decode(headers["PAYMENT-RESPONSE"]))
result = json.loads(body)
print("Paid on", receipt["network"], "transaction", receipt["transaction"])
print(result["organic"][0]["link"])
```

## The same call over MPP

The same search is also sold over MPP at `POST https://api.munition.io/v1/mpp/serper/search`: same body, same result, same price. Without an `Authorization: Payment` credential it answers `402` with a `WWW-Authenticate: Payment` challenge. See [MPP routes](/docs/payments/x402#mpp-routes).
