Part 4: Fighting FastAPI Quirks (And Winning!) A developer building a real-time data API that AI agents pay for via USDC micropayments over the x402 protocol documented two FastAPI workarounds needed to satisfy the protocol's strict schema. Because FastAPI's HTTPException wraps error payloads in a "detail" key, Coinbase's x402 verifier rejected the 402 challenge, so the developer replaced it with a custom exception and global handler returning a raw JSONResponse; the PAYMENT-RESPONSE receipt header was likewise lost when set in a dependency, and was fixed by stashing the receipt on request.state and attaching it in HTTP middleware after the endpoint responds. 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.