Roadmaps / AI Engineering / Lab 8

Lab 8 of 8 · Ship it: an API in a container

Serve the assistant as a tested API in Docker

Expose `/ask` with FastAPI, test it with the model faked out, run it in Docker with your key passed in safely, and run the tests in GitHub Actions.

Time
60–90 minutes
Cost
Free, apart from a fraction of a cent per question you ask.

What you learn

A notebook is not a product. Here you put the assistant behind a web API with input limits, package it in Docker, and test it automatically on every push without spending API credit.

  • Wrapping AI features in a web API
  • Input limits and safe error messages
  • Testing AI code with fakes, so CI is free
  • Passing secrets to containers at run time

In the AI era: Most AI engineering jobs are about this last mile: reliable, tested, observable services, not just good prompts.

Before you start

  • Finish lab 4.

  • Install Docker Desktop.

Step by step

  1. 1 Write the API

    The Field limits stop empty or huge questions before they cost money.

    File: api.py
    from fastapi import FastAPI
    from pydantic import BaseModel, Field
    
    import rag
    
    app = FastAPI(title="Docs Assistant")
    
    
    class Question(BaseModel):
        question: str = Field(min_length=3, max_length=500)
    
    
    @app.get("/health")
    def health() -> dict[str, str]:
        return {"status": "ok"}
    
    
    @app.post("/ask")
    def ask(body: Question) -> dict[str, str]:
        return {"answer": rag.answer(body.question)}
    
  2. 2 Test it with a fake model

    Replacing rag.answer means the test never calls Claude, so CI needs no key and costs nothing.

    File: tests/test_api.py
    from fastapi.testclient import TestClient
    
    import api
    
    client = TestClient(api.app)
    
    
    def test_ask_returns_the_answer(monkeypatch) -> None:
        monkeypatch.setattr(api.rag, "answer", lambda question: f"answer to: {question}")
        response = client.post("/ask", json={"question": "Do you ship to PO boxes?"})
        assert response.status_code == 200
        assert response.json() == {"answer": "answer to: Do you ship to PO boxes?"}
    
    
    def test_rejects_an_empty_question() -> None:
        assert client.post("/ask", json={"question": ""}).status_code == 422
    
  3. 3 Run all the tests

    None of these call the API.

    Run this
    python -m pytest -q
    You should see:

    7 passed.

  4. 4 Write the Dockerfile

    The key is not in the image: it is passed in when the container starts.

    File: Dockerfile
    FROM python:3.12-slim
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    COPY *.py ./
    COPY docs ./docs
    RUN useradd --create-home appuser
    USER appuser
    EXPOSE 8000
    CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]
    
  5. 5 Keep secrets out of the image

    This stops Docker from copying .env into the image.

    File: .dockerignore
    .venv
    .git
    .env
    __pycache__
    .pytest_cache
    tests
    
  6. 6 Build and run it

    --env-file .env hands your key to the container at run time.

    Run this
    docker build -t docs-assistant .
    docker run -d --name docs-assistant --env-file .env -p 8000:8000 docs-assistant
    curl -s -X POST http://localhost:8000/ask -H "content-type: application/json" -d '{"question": "How much is express shipping?"}'
    You should see:

    A JSON answer mentioning $12 and [shipping.md]. (The first question takes a little longer while the embedding model downloads.)

  7. 7 Run the tests on every push

    This workflow installs the project and runs the tests. No key is needed because the model is faked.

    File: .github/workflows/ci.yml
    name: CI
    
    on:
      push:
        branches: [main]
      pull_request:
    
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with:
              python-version: "3.12"
          - run: pip install -r requirements.txt
          - run: python -m pytest -q
          - run: docker build -t docs-assistant .
    
  8. 8 Push and clean up

    Watch the Actions tab turn green, then stop the container.

    Run this
    git add api.py tests Dockerfile .dockerignore .github
    git commit -m "Serve the assistant as a tested API in Docker"
    git push
    docker rm -f docs-assistant

You are done when

  • /ask answers through the container.

  • Seven tests pass locally and in GitHub Actions, with no key.

  • Your image does not contain .env (docker run --rm docs-assistant ls -a does not list it).

Finished? Get your proof page

We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.