Deploying with FastAPI and Docker
Turn your chatbot into a web service other apps can call, package it in a container that runs the same everywhere, and test it before it goes live.
1. Why it matters
- A notebook is not a product. Other teams, front ends and mobile apps need an API.
- "It works on my laptop" breaks in production; a container fixes the Python version and libraries.
- Interviewers for AI engineer roles expect you to have deployed something and to explain how.
2. Key ideas
3. How it works, step by step
- Wrap the RAG logic in functions that do not depend on the web layer (starter/rag.py).
- Add FastAPI endpoints: /health, /ask with a validated request model, /upload with size and type checks.
- Turn library errors into clear HTTP errors (400 bad input, 413 too large, 502 model provider problem).
- Write tests with FastAPI's TestClient; run them in CI.
- Write a Dockerfile: slim base image, install requirements, copy only what the app needs, run as a non-root user, add a health check.
- Build and run locally: docker build, docker run with --env-file .env, call /health and /ask.
- Deploy the image to a host, set the API key as a secret in the host's settings, and check /health on the public URL.
4. Code you can run
Run it from the starter project folder: uvicorn api.main:app --reload. It runs offline for free; add an API key in .env to use Claude.
"""FastAPI service for the PDF chatbot.
Run locally: uvicorn api.main:app --reload then open http://127.0.0.1:8000/docs
Endpoints: GET /health POST /ask {"question": "..."} POST /upload (a PDF file)"""
import os
import sys
import tempfile
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fastapi import FastAPI, File, HTTPException, UploadFile
from pydantic import BaseModel, Field
from starter import __version__
from starter.config import settings
from starter.rag import answer, index_pdf
SAMPLE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "sample_policy.pdf")
app = FastAPI(title="AI Master Course PDF chatbot", version=__version__)
state = {"store": index_pdf(SAMPLE), "document": "sample_policy.pdf"}
class Ask(BaseModel):
question: str = Field(min_length=3, max_length=500)
k: int = Field(default=3, ge=1, le=8)
@app.get("/health")
def health():
return {"status": "ok", "version": __version__, "mode": "offline" if settings.offline else "claude",
"model": "offline-stand-in" if settings.offline else settings.model,
"document": state["document"], "chunks": len(state["store"].items)}
@app.post("/ask")
def ask(body: Ask):
try:
return answer(state["store"], body.question, k=body.k)
except RuntimeError as e: # API problems are turned into readable messages in starter/llm.py
raise HTTPException(status_code=502, detail=str(e))
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
if not (file.filename or "").lower().endswith(".pdf"):
raise HTTPException(status_code=400, detail="Please upload a PDF file.")
data = await file.read()
if len(data) > 20 * 1024 * 1024:
raise HTTPException(status_code=413, detail="The PDF is larger than 20 MB.")
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, os.path.basename(file.filename))
with open(path, "wb") as f:
f.write(data)
try:
store = index_pdf(path)
except Exception as e:
raise HTTPException(status_code=400, detail=f"Could not read the PDF: {e}")
if not store.items:
raise HTTPException(status_code=400, detail="No text found. Scanned PDFs need OCR first.")
state.update(store=store, document=file.filename)
return {"document": file.filename, "chunks": len(store.items)}# The FastAPI service in a small image. Build: docker build -t pdf-chatbot .
FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir anthropic pypdf fastapi uvicorn python-multipart
COPY starter ./starter
COPY api ./api
COPY data ./data
RUN useradd --create-home appuser && mkdir -p logs && chown appuser logs
USER appuser
EXPOSE 8000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health')"
CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]GET /health -> {"status": "ok", "version": "1.0.0", "mode": "offline", "model": "offline-stand-in", "document": "sample_policy.pdf", "chunks": 5}
POST /ask -> 200 {"answer": "Passwords must be at least 14 characters. [S1]", "sources": [{"tag": "S1", "file": "sample_policy.pdf", "page": 2, "score": 0.149}], "refused": false}
POST /ask (too short) -> 422 String should have at least 3 characters
POST /upload notes.txt -> 400 Please upload a PDF file.5. What the code does
- The Ask model limits the question to 3 to 500 characters and k to 1 to 8; FastAPI returns 422 automatically when that fails.
- The store is built once at start-up and kept in memory, so each /ask call only embeds the question.
- /upload checks the file type and size before reading the PDF and refuses scanned PDFs with no text.
- The Dockerfile installs only what the API needs, runs as appuser and declares a health check.
- The output above comes from the real tests: TestClient calls, plus a docker build and run in the course's build environment (image about 250 MB).
6. Common mistakes and fixes
| Problem | Fix |
|---|---|
| API key baked into the image | Never COPY .env into the image. Pass it at run time or as a host secret; add .env to .dockerignore. |
| Index rebuilt on every request | Build at start-up or load a saved index. |
| Container listens on 127.0.0.1 | Inside a container use --host 0.0.0.0 or nothing outside can reach it. |
| Huge image | Use a slim base, --no-cache-dir and a .dockerignore; do not copy tests, notebooks or data you do not serve. |
| No timeout or error handling for the model call | Catch provider errors and return a clear message; set client timeouts. |
7. Product manager view
- Agree the API contract (inputs, outputs, errors) early so front end and back end can work in parallel.
- Ask where data is processed and stored; it decides which host and region are allowed.
- A health check and a rollback plan are launch requirements, not nice-to-haves.
8. Assignment
Check your work against the model answer for Subject 20.
9. Interview questions
Why FastAPI for an AI service?
It is fast to write, validates requests with type hints, generates interactive docs, and supports async calls, which suit slow model APIs.
How do you handle secrets in a container?
Pass them as environment variables or a secret manager at run time; never in code, the image or the repository.
What goes into a good Dockerfile for a Python API?
A slim pinned base, dependencies installed before the code for layer caching, only the needed files, a non-root user, a health check and a clear start command.
How would you scale this service?
Run several containers behind a load balancer, keep the index in a shared vector database instead of memory, add caching and rate limits, and watch p95 latency and cost.