DEV Community

Tam Edward
Tam Edward

Posted on Edited on

Part 3: Hybrid Auth in FastAPI — Supporting Both Human Developers and Autonomous AI Agents

Hybrid Auth
In the previous parts of this series we covered the product (real-time LLM pricing, performance and recommendation data for agents) and the payment layer (x402 micropayments). Now it’s time to talk about the thing that actually makes the two worlds coexist: authentication.

Most APIs are built for humans. They expect an API key, a JWT, or an OAuth token. Autonomous AI agents, especially those using x402, often show up with nothing. They expect to receive an HTTP 402 Payment Required challenge and then pay. If your auth layer blindly rejects every unauthenticated request with a 401, those agents never even get the chance to pay.

Here’s how I solved it in FastAPI without breaking existing human users.

The Real Constraint

I already had paying human developers using classic x-api-key headers. Their keys live in a PostgreSQL table and are checked on every request. I could not force them to migrate to crypto wallets overnight.

At the same time I needed agents to hit endpoints like /v1/prices/realtime with no Authorization header at all and receive a proper 402 response containing the x402 payment details.

FastAPI’s normal dependency injection makes this awkward. If you declare a required API key dependency, the framework short-circuits and returns 401 before your route code (or your x402 middleware) ever runs.

Making the API Key Optional

The first step is to make the key optional instead of required:

from fastapi import Depends, Header, HTTPException, Request
from typing import Optional

async def get_api_key(
    request: Request,
    x_api_key: Optional[str] = Header(None)
) -> Optional[str]:
    if not x_api_key:
        # Special case for agent endpoints
        if request.url.path.startswith("/v1/"):
            return None  # Let it through so x402 can take over
        raise HTTPException(
            status_code=401,
            detail="API key required",
            headers={"WWW-Authenticate": "ApiKey"},
        )

    # Normal human path: validate against database
    is_valid = await validate_api_key_in_db(x_api_key)
    if not is_valid:
        raise HTTPException(status_code=403, detail="Invalid API key")

    return x_api_key
Enter fullscreen mode Exit fullscreen mode

Then in your route:

@app.get("/v1/prices/realtime")
async def get_realtime_prices(
    provider: str,
    model: str,
    api_key: Optional[str] = Depends(get_api_key),
):
    if api_key is None:
        # This request is from an agent.
        # Your x402 middleware / dependency should have already
        # returned 402 by now if payment is required.
        # If we reach here, payment was successful or not required.
        return await fetch_prices(provider, model)

    # Human path — they already paid via subscription
    return await fetch_prices(provider, model)
Enter fullscreen mode Exit fullscreen mode

Where x402 Actually Lives

In practice I keep the x402 logic in a separate dependency or middleware that runs before the route body. The flow looks like this:

  1. Request arrives with no API key.
  2. get_api_key returns None (because path starts with /v1/).
  3. An x402 dependency (or middleware) checks whether payment is required for this endpoint.
  4. If payment is required and no valid payment header is present → return 402 with the challenge.
  5. If a valid x402 payment is attached → verify + settle via facilitator, then continue.
  6. If a valid traditional API key is present → skip x402 entirely and serve the request.

This keeps the two authentication worlds cleanly separated.

Things That Bit Me

  • Path matching is fragile. Hard-coding startswith("/v1/") works for now, but as soon as you add admin or webhook endpoints you need a better allow-list or a route-level flag.
  • Order of dependencies matters. If your x402 dependency is not ordered correctly, agents can slip past the paywall.
  • Logging and metrics. You want to distinguish “human with key”, “agent paid via x402”, and “agent failed to pay” in your logs. I added a simple request state flag for this.
  • Rate limiting. Agents paying per request and humans on a free tier need different rate-limit buckets. Don’t put them in the same bucket.

A Cleaner Pattern (What I Would Do Next)

Instead of path sniffing, I now prefer a route decorator or a dependency that explicitly declares the auth modes allowed:

def hybrid_auth(allow_x402: bool = False):
    async def dependency(request: Request, x_api_key: Optional[str] = Header(None)):
        if x_api_key:
            # validate key...
            return {"type": "api_key", "key": x_api_key}
        if allow_x402:
            return {"type": "x402"}
        raise HTTPException(status_code=401)
    return dependency
Enter fullscreen mode Exit fullscreen mode

Then:

@app.get("/v1/prices/realtime")
async def get_prices(
    auth = Depends(hybrid_auth(allow_x402=True))
):
    ...
Enter fullscreen mode Exit fullscreen mode

This makes the intent obvious at the route level and removes the magic path check.

Summary

Supporting both traditional API keys and x402 on the same FastAPI service is mostly about not letting the framework reject unauthenticated requests too early. Make the key optional, explicitly allow agents through on the endpoints that support x402, and let a dedicated x402 layer issue the 402 challenge.

It feels a little unconventional at first, but once it’s in place both human developers and autonomous agents can use the same endpoints without friction.


Have you built hybrid auth for agents and humans? What pattern did you end up with? I’d love to hear about it in the comments.

Next part I’ll show the actual x402 verification + settlement flow and how I keep the facilitator calls fast and reliable.

Top comments (0)