Skip to course content
Free FastAPI backend course

FastAPI for AI Backend Development

Unit 13.01: A fake that lets the whole suite run offline

A fake classifier lets the entire suite exercise the real request path.

Everything runs except the paid call

An endpoint whose real dependency raises, overridden with a fake.

The code shows a successful call and a validation failure.

from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field

app = FastAPI()


class Request(BaseModel):
    text: str = Field(min_length=1, max_length=4000)


def get_classifier():
    raise RuntimeError("real classifier not configured")


@app.post("/classify")
def classify(body: Request, classifier=Depends(get_classifier)) -> dict:
    return classifier(body.text)


app.dependency_overrides[get_classifier] = lambda: (
    lambda text: {"category": "billing", "confidence": 0.9})
client = TestClient(app)
print(client.post("/classify", json={"text": "charged twice"}).json())
print(f"validation still runs: {client.post('/classify', json={'text': ''}).status_code}")
app.dependency_overrides.clear()

print("\nRouting, validation, the response and error handling all ran.")
print("The only thing replaced was the part that costs money.")

Routing, validation, the response and error handling all ran. The only thing replaced was the part that costs money and needs a network.

The real dependency raising is deliberate: it means a test that forgets to override fails loudly rather than quietly making a paid call, which is the failure you want to be impossible.

The mistake this prevents

The mistake is a real dependency that falls back to a fake when no key is configured. It seems helpful and means a misconfigured production deployment silently serves fake predictions.

Takeaway

Override the model dependency in tests and let the real one fail loudly without configuration. A silent fallback to a fake is a production hazard.