Skip to main content

7 posts tagged with "FastAPI"

View all tags

Model Changed but Column Missing? 3 Alembic Pitfalls

ยท 7 min read

You add a field to a SQLAlchemy model in a FastAPI project using async SQLAlchemy. Everything works locally. After deploying, the first API call throws sqlalchemy.exc.ProgrammingError: column "xxx" does not exist โ€” the model changed, the table did not.

Encountered this while building an AI Agent SaaS platform for a client โ€” recording the root causes and fixes.

TL;DRโ€‹

When the model changed but the table didn't (or alembic won't even run), it is one of three pitfalls:

  1. Alembic still using the async engine โ€” Alembic does not run inside an event loop. env.py must switch to a sync URL (postgresql+asyncpg:// โ†’ postgresql://, psycopg2 driver)
  2. down_revision pointing at a revision ID that doesn't exist โ€” alembic upgrade fails with Can't locate revision
  3. Model edited, migration never generated โ€” the code looks right, the table is untouched, and production blows up on first use of the new column

The three pitfalls map to "migration won't run", "chain is broken", "migration was never created" โ€” in that triage order.

Symptomsโ€‹

Three symptoms, one per pitfall:

Symptom 1: production error after adding a model field

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) column "risk_threshold" does not exist

Works locally, fails on the first production query.

Symptom 2: the migration command itself fails

Can't locate revision identified by '001_initial'

alembic upgrade head never reaches your new migration.

Symptom 3: autogenerate reports no changes

Generating migration ...  (no changes in schema detected)

You definitely edited a model, yet alembic sees nothing โ€” usually env.py never imports your models, or it connects to the wrong database.

Root Cause 1: Alembic Running on an Async Engineโ€‹

Alembic migration scripts do not run inside an asyncio event loop. Your application can use async SQLAlchemy with the asyncpg driver, but the alembic command executes synchronously. If env.py reuses the app's async URL, the driver fails or behaves unpredictably.

The fix: give env.py its own sync engine. Swap postgresql+asyncpg:// for postgresql:// and install the psycopg2 driver.

pip install psycopg2-binary

Key part of alembic/env.py (after the config object is ready, before engine_from_config):

from sqlalchemy import pool, engine_from_config
from alembic import context

from app.config import settings
from app.database import Base
from app.models import * # noqa: F401,F403 - import all models

# Override sqlalchemy.url with sync URL for migrations
# Replace postgresql+asyncpg:// with postgresql:// for psycopg2
sync_url = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
config.set_main_option("sqlalchemy.url", sync_url)

Two details:

  • Replacing the async URL with the sync one via config.set_main_option() overrides the ini setting, so alembic.ini never needs a second connection string
  • The from app.models import * line is what registers every model into Base.metadata for autogenerate โ€” drop it and you get symptom 3, "no changes in schema detected"

On dependencies: psycopg2-binary must be installed in whatever environment runs alembic. It is easy to miss in CI or a container that only runs migrations.

Root Cause 2: A Broken down_revision Chainโ€‹

Alembic maintains a one-way linked list through revision / down_revision. upgrade head walks that chain from the current version to the tail. down_revision must reference a revision identifier that actually exists in the chain, character for character. A "close enough" name from memory breaks the link.

A real repository's chain, three files under alembic/versions/:

# 001_initial.py
revision = '001_initial'
down_revision = None

# 002_rename_model_config_to_llm_config.py
revision = '002_rename_model_config'
down_revision = '001_initial'

# 003_add_cascade_delete.py
revision = '003'
down_revision = '002_rename_model_config'

Can't locate revision identified by 'xxx' means some down_revision string does not resolve โ€” a wrong migration filename, half-copied ID, anything.

The fix is always the same two commands:

# 1. See the real chain (left column = revision ID)
alembic history

# 2. See where the database currently sits
alembic current

Point the new migration's down_revision at the real chain tail from alembic history, then alembic upgrade head. Alembic resumes from the position recorded in the alembic_version table; already-applied migrations do not re-run.

Use alembic history --verbose once the chain grows โ€” guessing the topology from filenames does not scale.

Watch out

Two developers branch in parallel and both write a migration whose down_revision points at the same parent โ€” upgrade head now reports multiple heads. Resolve it with alembic merge, which generates a merge migration. Our repository carries one such merge file, created to stitch two parallel branches. Multiple heads are not an anomaly; leaving them unmerged is.

Root Cause 3: Model Edited, Migration Never Createdโ€‹

The most common misconception: an ORM model is a code-level declaration and never modifies the database by itself. Adding a field to a model class:

class Agent(Base):
__tablename__ = "agent_agents"
# ...
risk_threshold = Column(String, default="medium") # new

This changes a Python object definition. The agent_agents table is untouched, and the first query referencing the column raises column does not exist. Locally it often "just works" because your dev environment built tables with create_all(), or a SQLite in-memory database is recreated each run โ€” both paths bypass migrations and mask the problem. Another model-layer trap is the Pydantic v2 ORM mode change; see Pydantic v2 ORM mode migration.

After any ORM model change, three fixed steps:

# 1. Generate a migration (autogenerate diffs model vs. database)
alembic revision --autogenerate -m "add risk_threshold to agent_agents"

# 2. Review the generated file by hand (autogenerate misses server defaults and
# constraint names; never upgrade blind)
# alembic/versions/xxxx_add_risk_threshold_to_agent_agents.py

# 3. Apply it
alembic upgrade head

Step 2 is not optional. Autogenerate is a diff tool with blind spots; upgrading its output unchecked is a gamble.

Verify the migration landed:

psql -c "\d agent_agents"   # confirm the new column exists
alembic current # confirm the version sits at the chain tail

Triage: Three Questionsโ€‹

For any "changed the model, table didn't move" problem (also searched as "column does not exist" or "field missing in table"), three questions locate it in a minute:

  1. Does the migration command run at all? No โ†’ pitfall 2, check the down_revision chain
  2. It runs, but the column is still missing? โ†’ pitfall 3, confirm autogenerate produced a file, upgrade head ran, and alembic current sits at the tail
  3. Connection or driver errors from alembic upgrade? โ†’ pitfall 1, the sync URL setup in env.py

One team rule on top: model changes and their migration files ship in the same commit. A model without its migration hands every collaborator the exact production error on pull.

FAQโ€‹

What are the basic alembic migration commands?โ€‹

Generate a migration with alembic revision --autogenerate -m "message", apply it with alembic upgrade head, roll back one step with alembic downgrade -1, and inspect the chain with alembic history. The standard workflow after any model change is exactly two steps: autogenerate, then upgrade head. Skip either one and the table stays unchanged.

I created my tables with SQLAlchemy โ€” why doesn't a model change take effect?โ€‹

A SQLAlchemy model is a code-level declaration only; it never touches the database. Alembic migrations own schema changes. Even if you built tables with create_all() locally, the new column lives in in-memory metadata โ€” production PostgreSQL raises ProgrammingError: column does not exist the first time a query touches it. Always generate a migration and run upgrade.

Why does alembic upgrade fail with Can't locate revision?โ€‹

Your down_revision references a revision identifier that does not exist in the chain โ€” usually a short name typed from memory. Run alembic history to get the real IDs, point the new migration's down_revision at the actual chain tail, then run alembic upgrade head. revision and down_revision must match character for character; one wrong character breaks the whole chain.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

FastAPI 422 or useParams Undefined? 4 Contract Mismatches

ยท 6 min read

Three classic scenes in frontend-backend integration: a POST returns 422; a route page's parameter stays undefined forever; an SSE request sits at 200 while the UI silently shows nothing. Different symptoms, one family of root causes โ€” the two sides disagreeing about the interface contract.

Encountered this while building an AI Agent SaaS platform for a client, frontend and backend developed in parallel โ€” we hit all four, and here is the locating method and the prevention discipline.

TL;DRโ€‹

Contract mismatches come in four shapes, producing three kinds of symptoms:

PitfallMismatchSymptom
Field namefrontend sends name, backend wants label422
Field typefrontend sends objects, backend expects List[str]422
Route paramroute defines :id, component reads agentIdundefined, feature silently dead
Event fieldbackend pushes {"content": ...}, frontend checks token200, UI shows nothing

Prevention is a single discipline: align on the schema before writing code โ€” field names, types, route param names, event data shapes, all sourced from the backend schema (or an interface doc both sides confirmed).

Pitfall 1: Field Name Mismatch โ†’ 422โ€‹

The most basic one. The frontend TypeScript interface declares name + key for creating an API key; the backend Pydantic schema expects label + api_key:

// what the frontend sends
interface CreateApiKeyInput {
name: string
key: string
}

# what the backend declares
class ApiKeyCreate(BaseModel):
label: str
api_key: str
POST /api/api-keys โ†’ 422 Unprocessable Entity

Locate it from the 422 response body โ€” don't guess. FastAPI's 422 carries a detail array spelling out every missing field and why:

[
{ "loc": ["body", "label"], "msg": "Field required", "type": "missing" },
{ "loc": ["body", "api_key"], "msg": "Field required", "type": "missing" }
]

Field required = the field is not in your request body at all = a field-name mismatch. Expand the response in the Network tab and it takes ten seconds.

Pitfall 2: Field Type Mismatch โ†’ 422โ€‹

Names can line up and types can still betray you. The backend declares mcp_tools as a list of strings; the frontend sends an array of objects (each with tool_id and token_id โ€” the business genuinely needs OAuth token binding):

// what the frontend sends
{ mcp_tools: [{ tool_id: "t1", token_id: "k1" }] }

# what the backend expects
mcp_tools: List[str]
PATCH /api/agents/{id} โ†’ 422 Unprocessable Entity

This time detail says Input should be a valid string โ€” a type mismatch. The fix is making the backend schema accept both shapes (the frontend's structure has a real business reason to exist; don't amputate it):

from typing import List, Union

class McpToolConfig(BaseModel):
tool_id: str
token_id: str | None = None

mcp_tools: List[Union[str, McpToolConfig]]

Union lets the schema accept both a plain string (tool reference only) and an object (with binding config); Pydantic tries them in order. The pattern generalizes to any "API evolves, frontend moves first" situation: the schema accommodates the real business shape, not the other way around.

Pitfall 3: useParams Name Mismatch โ†’ undefinedโ€‹

Route definition and component each written from memory, one word apart:

// route definition
<Route path="/agents/:id/memory" element={<MemoryPage />} />

// component
const { agentId } = useParams<{ agentId: string }>()
// agentId is undefined forever โ€” the route param is named id, not agentId

No error, status codes fine, feature silently dead โ€” agentId is undefined, so downstream API calls carry undefined or never fire.

Two fixes:

// 1. match the route definition
const { id } = useParams<{ id: string }>()

// 2. or rename while destructuring
const { id: agentId } = useParams<{ id: string }>()

What makes this one sneaky is the generic: useParams<{ agentId: string }> โ€” TypeScript does not verify that the keys in your generic actually exist in the route definition. The type annotation hands you false confidence.

Pitfall 4: Event Field Mismatch โ†’ 200 but Silent Failureโ€‹

In an SSE stream, the backend pushes {"content": "..."} while the frontend's event check looks for token:

// the frontend's event predicate
const isTokenEvent = (d: any) => 'token' in d // always false

// what the backend actually pushes
data: {"content": "hello"}

The Network tab shows 200 and the stream flowing; the UI shows nothing โ€” the predicate never fires and events are silently dropped. This one is harder to catch than a 422: no error, just a feature that never happens.

Fix: align the predicate with the backend's actual data shape:

const isTokenEvent = (d: any) => 'content' in d && !('type' in d)

For SSE/WebSocket interfaces carrying many event kinds over one connection, prefer an explicit type field for dispatching; inferring event kinds from "which keys happen to exist" turns every contract change into silent breakage.

Prevention: One Disciplineโ€‹

All four pitfalls share an origin: each side wrote its half of the interface from imagination. Prevention needs no tooling, one discipline โ€”

Before writing any interface code, align on the schema: field names, types, route param names, event shapes โ€” item by item. The backend Pydantic schema (or OpenAPI doc) is the single source of truth; the frontend TypeScript interfaces mirror it. Whoever changes the contract changes the schema first, both sides confirm, then code moves.

When symptoms appear, triage in order: 422 โ†’ expand the response detail and read loc; undefined โ†’ check the route's :param names; 200 but nothing happened โ†’ capture a real response and diff it field-by-field against the frontend predicate.

The server side of streaming interfaces has a companion pitfall (exceptions and leaked resources on client disconnect), covered in FastAPI SSE CancelledError on Client Disconnect? Catch and Re-raise in the Generator.

Watch out

Frontend TypeScript interfaces (interface XxxInput) are compile-time paper constraints โ€” as any and third-party request wrappers can bypass them entirely. Types matching does not mean fields matching. The final arbiter of contract truth is always a comparison against the backend schema, not the absence of red squiggles.

FAQโ€‹

Why does FastAPI return 422 Unprocessable Entity?โ€‹

In 9 out of 10 cases the request body does not match the Pydantic schema: a field name the backend does not expect (sending name when the schema wants label) or a field type mismatch (an array of objects where List[str] is declared). The 422 response body lists every offending field in its detail array โ€” read it before guessing.

How do I debug which field caused a FastAPI 422?โ€‹

Open the response body in the browser Network tab or curl: FastAPI returns a detail array where each entry has loc (the field path), msg (Field required / Input should be a valid string), and type. loc pointing at a field you did send under a different name is the classic field-name mismatch.

Why does useParams return undefined in React Router?โ€‹

The keys of useParams come from the route definition: a route of /agents/:id exposes only id. Destructuring a name that does not appear in any :param โ€” like agentId โ€” yields undefined silently, no error thrown. Rename during destructuring instead: const { id: agentId } = useParams().

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Python task marked failed but no error? try/except swallowed the exception

ยท 5 min read

Debugging a silent failure where a document sync task marked everything failed in a RAG knowledge base project โ€” full writeup below.

TL;DRโ€‹

A shared method was refactored with a new parameter signature, but one caller was missed. The caller passed arguments under the old contract and threw TypeError โ€” except the call sat inside a try/except that quietly funneled the exception into a failed counter. No crash, no ERROR in the logs, just a number ticking up. These "silent failures" are the hardest bugs to track down. Two fixes: grep all callers after a signature refactor; and make except blocks log or re-raise, never swallow silently.

Unify Multiple Search APIs with Abstract Class, Return Errors Instead of Raising

ยท 4 min read

Encountered this issue while building an AI Agent platform for a client: needed to support multiple search providers (Tavily, Serper, Brave, Bing) while ensuring tool call failures don't interrupt the Agent's conversation flow.

TL;DRโ€‹

  1. Define SearchProvider abstract base class + SearchResult data model for unified interface and output
  2. Each provider inherits the base class, implements search() method with field mapping
  3. Key design: Return SearchResult with error info on failure, never raise exceptions

Fixing CancelledError When FastAPI SSE Clients Disconnect

ยท 2 min read

Encountered this while building an AI customer-service automation system for a client โ€” recording the root cause and fix.

TL;DRโ€‹

FastAPI's StreamingResponse cancels the generator task when the client disconnects, raising asyncio.CancelledError. The correct fix is to catch the exception inside the generator and re-raise โ€” otherwise you get error-log noise and resource leaks.

Three Pitfalls Integrating Supabase Auth with FastAPI

ยท 4 min read

Encountered this while building a SaaS authentication system for a client โ€” recording the root causes and fixes.

TL;DRโ€‹

Supabase Auth + FastAPI integration has three common pitfalls: the JWKS path is not the standard one, ES256 signatures need conversion to DER format, and first-time users have no local database record. Complete solutions below.