Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Testing

Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why

There's no test suite yet, so test the running Gemma chat app by hand in a fixed order: weights staged, images built, backend answers (and refuses with a reason), pages load, logs clean. Add a global exception handler so a dead Supabase shows 'ConnectError: connection refused', and end with a list of what still fails.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Testing

What you will learn

  • Run a fixed, five-step manual check on a running FastAPI, Celery and React stack
  • Stage model weights once into a mounted volume with a download script, before the build
  • Add a catch-all exception handler so every 500 carries its reason to the UI
  • Spot how the same checks look in the Django and Flask versions of the backend

Before you start

  • Dockerizing the local LLM chat stack
  • FastAPI routes and HTTPException

We built the Gemma chat app and put it into Docker. Now we test it, before we build anything more on top.

This project has no test suite yet, so there are no test files to run. Instead we test the running app by hand, in a fixed order, and whatever fails goes on a list for the next prompts.

Manual test order 1. weights staged 2. build all containers up 3. backend no, with a reason 4. React pages load 5. logs clean anything that fails goes on the fix list
The same order every time, so a failure points at one layer.

1. Get the weights ready before the build

The app gets Gemma's weights from Kaggle Hub, so Kaggle needs to know who you are. requirements-ml.txt pins kagglehub 0.4.1 or newer, which is needed for the newer API token. On Kaggle, open your account settings, generate a new API token under API tokens (it's a single value, no username), and accept the Gemma licence on the model page once. Paste the token into .env on the KAGGLE_API_TOKEN line. Keep that file out of git.

Now, where should the download happen? If it happens during the Docker build or when the app starts, every rebuild can fetch the weights again, and a slow network can break the build. Better: download once into a local folder before anything runs. That folder is model-cache in the backend, and compose mounts it into both the API and the worker at /app/model-cache. A volume isn't rebuilt with the image, so the weights stay put.

We asked Claude Code for a script:

Role: A Python backend developer. Context: A FastAPI backend whose model settings are in the .env file. Task: Write a script that downloads the configured model into the backend's own model-cache folder, so the Docker build and the running app never have to download it. Format: One Python file in the backend folder, and the command to run it.

If it asks how to store the weights, pick a local download with a volume. Here's the core of download_model.py:

def main() -> int:
    print(f"  DEFAULT_MODEL_SLUG : {settings.default_model_slug}")
    print(f"  MODEL_CACHE_DIR    : {settings.model_cache_dir}")
    # ...

    try:
        path = ensure_model_available()
    except Exception as exc:  # noqa: BLE001 - surface the reason, fail the script
        print(f"\nERROR: could not download / stage the model: {exc}", file=sys.stderr)
        return 1

    if not _has_model_files(path):
        print(
            f"\nERROR: no model files (config.json) found at {path} after staging. "
            "If you set MODEL_PATH, make sure the weights actually live there.",
            file=sys.stderr,
        )
        return 1

    print(f"\nModel staged at: {path}")
    return 0

It prints the model slug and cache folder, fetches the weights, checks that a config.json is really there, and returns 1 on any failure so the script fails clearly. Running it in the lecture went like this:

cd backend
python download_model.py      # on Windows: py download_model.py
  1. First try: "kagglehub is not installed". The base requirements file doesn't have it; it lives in requirements-ml.txt. pip install kagglehub into the backend's virtual environment.
  2. Second try: Kaggle answers 403, no permission to access the resource. That's what an empty token or an unaccepted licence gives you.
  3. Token added, licence accepted: it ends with Model staged at: and a path inside model-cache.

While it downloads: make errors carry a reason

We gave the agent a second job, an audit: keep only user management, chat and chat history, keep it simple, and make sure every error reaches the UI with its reason. Three changes came back:

  • An error handler in main.py.
  • A React error page, app/error.tsx, with the message and a Try again button instead of a blank screen.
  • A fix in config.py: an empty MODEL_CACHE_DIR= line used to leave the cache folder empty, so the weights landed outside the volume and downloaded again on every start. Now an empty value falls back to the default folder.

The handler changes how we test. Without it, an error no route catches comes back as a bare 500, and the front end can only say the request failed.

@app.exception_handler(Exception)
async def unhandled_exception_handler(_request: Request, exc: Exception) -> JSONResponse:
    """Turn any uncaught error into a JSON ``{detail: ...}`` 500."""
    logger.exception("Unhandled error: %s", exc)
    return JSONResponse(
        status_code=500,
        content={"detail": f"{type(exc).__name__}: {exc}"},
    )

logger.exception sends the full traceback to the API log. The response carries the error's type and message in detail. On the React side, chat-api.ts reads it and throws it as the error message:

    return data.detail || data.message || data.error || null;

2. Build and start

docker compose up --build

This build takes a while. The backend image installs PyTorch built for NVIDIA CUDA, and that download is large: the API image came out at 11.73 GB, and the worker uses the same image. The front end is about 300 MB, Redis much smaller. Check your disk space first. The image targets NVIDIA cards; with another kind of GPU the GPU path won't work as it is (the GPU gets its own step later). Four containers come up: Redis healthy on 6379, the API on 8000, the worker running, the front end on 3000.

3. The backend says no, with a reason

Open localhost:8000/docs. Swagger lists every route.

RequestAnswer
GET health200, status ok, flavor fastapi
conversations, no token401, missing authorization header
conversations, wrong secret401, signature verification failed
conversations, old token401, token has expired
POST chat, empty body422, names the two missing fields: content and model_slug

Now one that fails on purpose. Point the Supabase address in .env at a place where nothing runs, and call get models with Try it out. You get a 500, but the body says ConnectError: connection refused. That's the handler at work, and the API log has the full traceback. Here, the backend can't reach Supabase, and the message tells you where to look.

4. The React pages

localhost:3000 loads. The login page has Continue with Google, email and password, and the hCaptcha box, which says it's for testing only because .env still has the public test site key. Open /chat signed out, and the middleware sends you to login with redirectTo=/chat. Pages load, the protected page stays protected.

5. The logs

docker compose logs frontend
docker compose logs api
docker compose logs worker

Front end: Next.js ready on port 3000. API: Uvicorn running on 8000, plus the unhandled error we just caused. The worker log is the one to watch. With the real engine on and no token, the worker tries to fetch the model, gets the same 403, prints a warning, and still says ready. So the worker looks fine and the problem only shows on the first chat message. Read the logs; don't trust "ready" on its own.

The fix list

  1. Front-end URLs. The backend URL, the Supabase URL and the hCaptcha site key are baked into the browser code at build time. Wrong values send you to the wrong place, and changing .env alone doesn't help. You have to rebuild.
  2. hCaptcha. Still on the test key.
  3. Chat. The message goes out, the page keeps polling, no reply comes back. One likely cause is the one in the worker log: a model that never loaded.

Those get fixed in the next round.

The same checks with Django or Flask

The order stays the same, and the React pages and model download work the same way. What changes is in the backend.

FastAPIDjangoFlask
Swagger/docs/api/schema/swagger-ui (drf-spectacular)not covered in the lecture
Built-in checksnone yetmanage.py test (0 tests, OK) and manage.py check (no issues)create_app() gives a test client; five pytest checks pass in about 3 s
No token401, missing authorization header401, authentication required401
Empty chat body422400 from the serializer, both fields named422, Marshmallow lists both fields under errors
Reason fielddetailuncaught errors: HTML page (no handler)message
Uncaught errorJSON 500 via the handler500 as text/html; read the API logJSON 500 once you add the handler below

In Django, with debug on (the project default), an uncaught error returns Django's HTML error page; with debug off it's just "server error". Keep debug off anywhere but your own machine. Because chat-api.ts can't read JSON from an HTML page, the UI only shows "chat request failed" and the status. To get the reason into the UI, Django REST framework lets you set your own exception handler in settings.py.

In Flask, app/__init__.py has a create_app() factory; wsgi.py calls it once and Gunicorn runs it with two workers. Its image installs only the base requirements (the ML line is commented out) and is about 290 MB, against 11.73 GB for FastAPI. The lecture adds a handler inside create_app():

    @app.errorhandler(Exception)
    def handle_unexpected_error(exc):
        if isinstance(exc, HTTPException):
            return exc
        logger.exception("Unhandled error: %s", exc)
        return jsonify(message=f"{type(exc).__name__}: {exc}"), 500

HTTP exceptions pass through, so the 401s and the 422 don't change. Anything else is logged and returned as a 500 with a message, and the same call now says connect error, connection refused. The React side needs no change, because it reads detail, then message.

Common mistakes

  • Downloading weights inside the build. Every rebuild risks fetching gigabytes again.
  • Trusting "ready" in the worker log. It can be ready with no model loaded.
  • A bare 500. Without a handler, the UI can't tell a dead database from a bad request.
  • Debug on in Django outside your machine. The HTML error page shows internals.

Quick recap

CheckWhat passing looks like
WeightsModel staged at a path in model-cache
Buildfour containers, Redis healthy
Backend200 on health; 401 and 422 with reasons; 500 with detail
Pageslogin loads, /chat redirects when signed out
Logsno surprise warnings, especially in the worker

Try it yourself

Pick one of the three issues on the list, write a prompt to fix it, rebuild, and check it again in the same order.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 39 of 39

Previous
Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure

Seventeen pytest tests for the FastAPI blog. conftest.py builds a fresh test.db in tmp_path and swaps get_db with dependency_overrides, fixtures log in an admin and a reader, and the tests check pages, login, register, the admin-only write route and bcrypt's 72-byte limit. blog.db stays untouched.

On this page

  • 1. Get the weights ready before the build
  • While it downloads: make errors carry a reason
  • 2. Build and start
  • 3. The backend says no, with a reason
  • 4. The React pages
  • 5. The logs
  • The fix list
  • The same checks with Django or Flask
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.