</>CodeWithKarani
All topics
Topic

Python & FastAPI

30 articles in this topic.

AI Engineering6 min read

Metering, model routing and the regression suite that stops your agent rotting

Two questions decide whether an AI feature survives its first year: does each request make money, and will a prompt edit break something silently? An append-only credit ledger, two-tier routing, and a suite that asserts question-to-metric mappings are the answers.

Read
AI Engineering6 min read

Shipping a business agent on WhatsApp: templates, webhooks and the 24-hour window

The in-app chat panel was good and nobody opened it. Putting the agent on WhatsApp means the Cloud API's template rules, idempotent webhooks, per-tenant scheduled jobs, alert hysteresis, and testing that Sheng routes to the right metric.

Read
AI Engineering6 min read

Hosted brain, dumb connector: splitting an AI agent so the data never leaves the client

Ship your agent to the client and you hand over your product. Pull their data to your platform and you become the custodian of their business records. The third option is a split: a hosted brain that decides what to fetch, and an on-prem connector with no intelligence in it at all.

Read
Payments & Fintech7 min read

M-Pesa "Invalid BusinessShortCode": The Python requests Bug Behind It

Daraja error 400.002.02 blames your shortcode, but the real cause is usually data=payload instead of json=payload in Python requests. Here is how to prove it.

Read
Python & FastAPI8 min read

Celery's unresolved worker memory leak: what actually helps when nothing fixes it

Celery's parent process RAM climbs for days with no confirmed cause upstream. Here is what the open issue really says, and the mitigations that hold your server up meanwhile.

Read
Python & FastAPI8 min read

The asyncio SSL Memory Leak Nobody Warns You About, and How to Work Around It

Long-running asyncio TLS services can leak memory in the SSL transport, growing RSS until the OOM killer strikes. Here is how to confirm it, mitigate it, and track the real fix.

Read
Python & FastAPI8 min read

FastAPI 422 Unprocessable Entity: Read the Error Body Instead of Guessing

FastAPI already tells you exactly which field is wrong in the 422 response body. Stop relaxing validation. Read detail[].loc, and fix the three payload mistakes that cause almost every 422.

Read
Python & FastAPI7 min read

Pydantic v1 to v2 Migration Gotchas the Official Guide Leaves Out

The Pydantic v2 migration guide misses two real traps: a moved ModelMetaclass import and a silent datetime coercion change that breaks tests without raising. Here is both.

Read
Python & FastAPI7 min read

Pydantic mypy plugin: the false 'Unexpected keyword argument' on forbid-extra models

The pydantic mypy plugin can report Unexpected keyword argument on correct code that mixes type aliases with extra='forbid'. It is a known plugin limitation, not your bug. Here is the scoped fix.

Read
Python & FastAPI9 min read

pytest-asyncio 'event loop is already running': there is no patch coming

request.getfixturevalue() on an async fixture crashes pytest-asyncio, nest_asyncio no longer saves you, and upstream has no fix. Here is the test architecture that works instead.

Read
Python & FastAPI6 min read

Pydantic v2 'MockValSer object cannot be converted to SchemaSerializer': The Real Cause

This cryptic Pydantic v2 TypeError means your model schema never finished building, usually an unresolved forward reference. Here is the fix, not a workaround.

Read
Python & FastAPI9 min read

QueuePool Limit Reached Under FastAPI Load: pool_size Is Not the Fix

The SQLAlchemy QueuePool timeout under FastAPI load is about how long connections are held, not how many exist. Why raising pool_size fails, and the async session scoping that works.

Read
Python & FastAPI7 min read

Uvicorn's 'uvicorn.error' Logger Is Not About Errors: Stop the False Alarms

Uvicorn tags routine INFO logs with the logger name uvicorn.error, tripping monitors that pattern-match on 'error'. Here is why, and how to alert on severity instead.

Read
Python & FastAPI9 min read

Error loading ASGI app: why uvicorn cannot import your FastAPI module

Uvicorn resolves 'module:app' against sys.path, not your file's location. The real cause, the right command for flat, package, src and Docker layouts, and how to verify it.

Read
Python & FastAPI6 min read

FastAPI Cross-Site Cookies Silently Not Set: SameSite and Secure

Your FastAPI set_cookie returns 200 but the browser never stores it and there is no error. Here is why cross-site cookies need SameSite=None; Secure, and how to fix it.

Read
Python & FastAPI5 min read

FastAPI CORS Silently Failing: the allow_credentials Plus Wildcard Trap

FastAPI CORS with allow_credentials=True and allow_origins=['*'] passes testing then breaks once cookies flow. The browser blocks it silently. Here is why and the fix.

Read
Python & FastAPI8 min read

Turn FastAPI Validation Errors Into Clean Per-Field Messages

FastAPI's default 422 body is a nested Pydantic list no frontend can use. Here is a RequestValidationError handler that flattens it to clean per-field messages without breaking on upgrade.

Read
Python & FastAPI7 min read

FastAPI Memory Leaks in Production: A Root-Cause Checklist

FastAPI workers whose memory climbs to OOM usually are not leaking, they are blocking the event loop or queuing unbounded work. A checklist to find the real cause before blaming the framework.

Read
Python & FastAPI7 min read

Why Your FastAPI Logs Vanish Under Gunicorn and Uvicorn (and the Config That Works Everywhere)

FastAPI logs work in local dev but disappear in Docker under gunicorn+uvicorn, especially below WARNING. The cause is disable_existing_loggers and uvicorn's own loggers. Here is the fix.

Read
Frappe/ERPNext6 min read

'Can't pickle LazyUser' With frappe.enqueue: The Background Job Rule Everyone Breaks

frappe.enqueue pickles its arguments, and a Frappe Document drags in a LazyUser pickle cannot handle. Pass doctype and name strings and re-fetch inside the job.

Read
Python & FastAPI8 min read

FastAPI yield Dependencies: How Cleanup Works and Where It Silently Breaks

FastAPI 0.106 moved yield-dependency teardown to run before the response, silently breaking background tasks and middleware commits. Here is the fix that survives upgrades.

Read
AI Engineering6 min read

Why RetryError hides the real reason your LLM call failed

A tenacity RetryError buries whether your LLM call died from a rate limit, bad auth or a timeout. And raw httpcore errors leak through elsewhere. Here is a typed boundary that fixes both.

Read
Python & FastAPI6 min read

ModuleNotFoundError: No module named 'fastapi' - the Three Unrelated Causes

One error message, three completely different causes: wrong virtualenv, package not installed, or a stale editable install left behind by switching between pip, poetry and uv.

Read
Python & FastAPI7 min read

'No module named pydantic_core._pydantic_core' in Docker or Lambda Is an Architecture Mismatch

This error is not a missing package. pydantic-core ships a compiled Rust wheel, and installing it for the wrong CPU or glibc means the files exist but cannot load.

Read
Python & FastAPI6 min read

pip 'externally-managed-environment': What PEP 668 Protects and the Right Fix

The externally-managed-environment error is PEP 668 stopping pip from corrupting your OS packages. Use a venv, not --break-system-packages, and here is exactly why --user is not reliable.

Read
Python & FastAPI7 min read

Why Your FastAPI 'async' Endpoints Run in Serial: The Blocking Event Loop Trap

FastAPI processing requests one at a time? async def does not make blocking code async. Here is why the event loop serialises, and the def vs async fix.

Read
Python & FastAPI7 min read

Celery Task Received but Not Executing: The Four Real Causes

Celery logs 'Received task' then runs nothing, with no error. It is one symptom with four unrelated causes. How to tell them apart with py-spy instead of guessing at flags.

Read
Frappe/ERPNext7 min read

cannot import name 'Table' from 'frappe.query_builder': Use DocType

The frappe.query_builder rewrite around pypika dropped Table with no shim. Here is the correct import, the root cause, and version-tolerant code that survives upgrades.

Read
Linux & Servers6 min read

python: command not found on Ubuntu 20.04, and Why You Should Not Symlink It

Ubuntu 20.04 ships no /usr/bin/python at all, so scripts and deploy jobs die with command not found. The correct fixes, and why the popular ln -s answer causes a worse bug later.

Read
Python & FastAPI6 min read

Python 2 Dies in January: The Migration Plan I Wish I Had Started Sooner

Python 2 reaches end of life on 1 January 2020. Here is the order I move a real codebase in, the bugs that only appear in production, and what to do if you truly cannot finish.

Read