# Part 4: Fighting FastAPI Quirks (And Winning!)

> Source: <https://dev.to/edwardtam919/part-4-fighting-fastapi-quirks-and-winning-1kfg>
> Published: 2026-11-24 08:09:44+00:00

**Recommendation:** When implementing x402 payment challenges in FastAPI, bypass HTTPException with a custom exception returning a raw JSONResponse, and attach PAYMENT-RESPONSE receipts in middleware via request.state so they survive the response lifecycle.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

Welcome to Part 4 of building a real-time data API that AI agents can pay for with USDC micropayments via the x402 protocol.

This week was less about shipping features and more about wrestling with FastAPI’s opinionated defaults. I’m not a FastAPI expert, so a couple of its “helpful” behaviors caused real friction with the strict requirements of x402. Here’s what broke, why it broke, and how I fixed it.

The x402 protocol is strict. When an agent hits an unpaid endpoint, you must return HTTP 402 with a JSON body whose root keys match the challenge format exactly (typically `accepts`, `resource`, and related fields). No wrapping allowed.

My first attempt used FastAPI’s standard exception:

```
raise HTTPException(
    status_code=402,
    detail={
        "accepts": [...],
        "resource": "...",
        # other x402 fields
    }
)
```

FastAPI automatically wraps the payload like this:

```
{
  "detail": {
    "accepts": [...],
    "resource": "..."
  }
}
```

Coinbase’s x402 verifier immediately rejected the response. The extra nesting is a hard fail.

FastAPI’s `HTTPException` is designed for human-friendly error responses. It assumes most clients want a consistent `{ "detail": ... }` shape so error handling is uniform across an API. That’s usually a good idea — until you’re speaking a machine protocol that defines its own exact schema.

I bypassed `HTTPException` for the 402 challenge with a custom exception:

``` python
class X402PaymentRequiredException(Exception):
    def __init__(self, payload: dict, headers: dict):
        self.payload = payload
        self.headers = headers
```

In the dependency I raise it with the raw challenge payload:

```
challenge = get_x402_challenge_payload(str(request.url), amount, request.url.path)

headers = {}
# ... optional PAYMENT-REQUIRED header ...
raise X402PaymentRequiredException(payload=challenge, headers=headers)
```

A global exception handler then returns a raw `JSONResponse` with the payload at the root level (no `"detail"` wrapper). Normal `HTTPException` handling stays in place for all other errors.

After an agent successfully pays, the x402 spec requires you to return a receipt in the `PAYMENT-RESPONSE` response header.

I tried setting the header inside the dependency that verifies and settles the payment. It never appeared in the final response.

When your endpoint function returns a response (or FastAPI constructs one for you), headers that were attached earlier in the dependency chain can be discarded. FastAPI’s response lifecycle is:

Anything you mutate on an intermediate response object can get overwritten or ignored once the endpoint returns its own response.

`request.state` + Middleware
I stored the receipt on `request.state` inside the dependency, then used a global HTTP middleware to attach it at the very end.

In the payment dependency (after successful verify + settle):

```
if is_valid:
    # Save the receipt to the request state so the middleware can catch it
    request.state.payment_receipt = tx_hash or "settled"
    return {"is_x402": True, "tx_hash": tx_hash}
```

Middleware (registered with `@app.middleware("http")`):

``` python
@app.middleware("http")
async def add_x402_receipt_header(request: Request, call_next):
    response = await call_next(request)

    receipt = getattr(request.state, "payment_receipt", None)
    if receipt:
        response.headers["PAYMENT-RESPONSE"] = receipt

    return response
```

This runs after the endpoint has produced its final response, so the header sticks.

Next week I’ll cover how AI agents actually discover and decide to call an x402-protected endpoint in the wild.

Have you run into similar FastAPI surprises when integrating strict external protocols? Drop a comment — I’d love to hear how you handled them.
