priyanka Claude Opus 4.6 commited on
Commit
79fcd5e
·
1 Parent(s): 80e72db

Rebuild repo as REST-API-Builder tutorial

Browse files

Replace the old step-based structure with a 6-lab hands-on tutorial
that teaches REST fundamentals, builds a clinical urgency classifier,
exposes it as a FastAPI REST API, tests with pytest, and deploys via
Render/HuggingFace/Docker. Uses modern tooling (uv, ruff, pyproject.toml).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "REST-API-Builder",
3
+ "image": "mcr.microsoft.com/devcontainers/python:3.11",
4
+ "postCreateCommand": "pip install uv && uv sync --extra dev",
5
+ "forwardPorts": [8000, 7860],
6
+ "customizations": {
7
+ "vscode": {
8
+ "extensions": [
9
+ "ms-python.python",
10
+ "ms-python.vscode-pylance",
11
+ "humao.rest-client",
12
+ "rangav.vscode-thunder-client"
13
+ ],
14
+ "settings": {
15
+ "python.defaultInterpreterPath": "/usr/local/bin/python"
16
+ }
17
+ }
18
+ }
19
+ }
.gitignore ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ *.egg-info/
7
+ dist/
8
+ build/
9
+ *.egg
10
+
11
+ # Virtual environments
12
+ venv/
13
+ env/
14
+ .venv/
15
+
16
+ # IDE
17
+ .vscode/
18
+ .idea/
19
+ *.swp
20
+ *.swo
21
+
22
+ # OS
23
+ .DS_Store
24
+ Thumbs.db
25
+
26
+ # Model artifacts (generated by training)
27
+ models/*.joblib
28
+ models/*.json
29
+ !models/README.md
30
+
31
+ # Environment variables
32
+ .env
33
+ .env.local
34
+
35
+ # Jupyter
36
+ .ipynb_checkpoints/
37
+
38
+ # uv
39
+ uv.lock
40
+
41
+ # pytest
42
+ .pytest_cache/
43
+ htmlcov/
44
+ .coverage
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # Dockerfile — REST-API-Builder
3
+ # ============================================================
4
+ # This Dockerfile does three things:
5
+ # 1. Installs Python dependencies
6
+ # 2. Trains the ML model at BUILD time (so it's baked into the image)
7
+ # 3. Runs the production FastAPI server
8
+ #
9
+ # Works with:
10
+ # - HuggingFace Spaces (port 7860)
11
+ # - Any Docker host (docker run -p 7860:7860)
12
+ #
13
+ # Build & run locally:
14
+ # docker build -t rest-api-builder .
15
+ # docker run -p 7860:7860 rest-api-builder
16
+ # ============================================================
17
+
18
+ FROM python:3.11-slim
19
+
20
+ # Set working directory inside the container
21
+ WORKDIR /app
22
+
23
+ # Install uv — a fast Python package manager written in Rust
24
+ RUN pip install --no-cache-dir uv
25
+
26
+ # Copy dependency files first (Docker caches this layer if deps don't change)
27
+ COPY pyproject.toml .
28
+
29
+ # Copy the entire project
30
+ COPY . .
31
+
32
+ # Install dependencies using uv
33
+ RUN uv sync --no-dev
34
+
35
+ # Train the model at build time so it's ready when the container starts
36
+ RUN python lab_02_train_model/train.py
37
+
38
+ # HuggingFace Spaces expects port 7860
39
+ EXPOSE 7860
40
+
41
+ # Run the production-ready app
42
+ CMD ["uvicorn", "lab_05_deploy.app:app", "--host", "0.0.0.0", "--port", "7860"]
LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 po-DRA
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,258 +1,167 @@
1
- # 🏥 API Tutorial with ML model usage
2
- ### *From Zero to Deployed in 60 Minutes*
3
 
4
- > **Built for:** Researchers with basic Python knowledge
5
- > **Goal:** Build a real NLP API that extracts entities from clinical notes and deploy it publicly
6
- > **Time:** ~1 hour | **Platform:** GitHub Codespaces (zero local setup needed)
7
 
8
- ---
9
-
10
- ## ⚡ Start in 30 Seconds (No Setup Required)
11
-
12
- Click the button below to open this repo in a **cloud development environment** : Python, all dependencies, and VS Code, all ready instantly:
13
-
14
- [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/po-DRA/API)
15
-
16
- > **Don't have Codespaces?** GitHub gives you 60 free hours/month.
17
- > Or clone and run locally: `git clone ... && pip install -r requirements.txt`
18
 
19
  ---
20
- <img width="2250" height="2752" alt="image" src="https://github.com/user-attachments/assets/d75bc383-d603-4cf2-b0a0-e5588d620a01" />
21
- [🔗](https://bytebytego.com/guides/the-ultimate-api-learning-roadmap/)
22
-
23
 
24
- ## 🗺️ The 1-Hour Roadmap
25
 
26
- ```
27
- ┌────────────────────────────────────────────────────────────────────┐
28
- │ │
29
- │ ⏱ 0:00 Step 0 — Concepts (10 min) │
30
- │ What is an API? When to use one? Key patterns. │
31
- │ │
32
- │ ⏱ 0:10 Step 1 — Hello API (10 min) │
33
- │ Your first running FastAPI server. GET + POST. │
34
- │ │
35
- │ ⏱ 0:20 Step 2 — Real Medical NLP (15 min) │
36
- │ HuggingFace NER model. Live inference. Zero-shot. │
37
- │ │
38
- │ ⏱ 0:35 Step 3 — Background Tasks (10 min) │
39
- │ For slow models: submit job → poll → get results. │
40
- │ │
41
- │ ⏱ 0:45 Step 4 — Deploy to Render (10 min) │
42
- │ Push to GitHub → live public URL → share with world. │
43
- │ │
44
- │ ⏱ 0:55 Bonus — Choose Your Own Adventure │
45
- │ Streamlit UI, batch processing, fine-tuning & more. │
46
- │ │
47
- └────────────────────────────────────────────────────────────────────┘
48
- ```
49
 
50
  ---
51
 
52
- ## ❓ The Questions This Tutorial Answers
53
 
54
- > *"What sort of projects are appropriate for APIs?"*
55
-
56
- Anything you want to call automatically, repeatedly, or from other tools:
57
- - Extract diagnoses from clinical notes → **API**
58
- - Classify urgency of incoming referrals → **API**
59
- - Identify drug interactions in a prescription → **API**
60
- - Summarize a patient's history for a new specialist → **API**
61
-
62
- > *"Can the model run in the background, or does it need pre-existing results?"*
63
-
64
- **Both options are covered** — you'll build all three patterns:
65
-
66
- | Pattern | When to use | Covered in |
67
- |---------|------------|-----------|
68
- | **Live inference** | Fast model (<3s), interactive use | Step 2 |
69
- | **Pre-computed** | Results don't change, need speed | Step 2 (demo mode) |
70
- | **Background jobs** | Slow model (>5s), batch processing | Step 3 |
71
 
72
  ---
73
 
74
- ## 📁 Repo Structure
75
 
76
- ```
77
- api/
78
- │
79
- ├── 📖 README.md ← You are here
80
- │
81
- ├── 🧠 step_00_concepts/
82
- │ └── README.md ← API theory, no code
83
- │
84
- ├── 🚀 step_01_hello_api/
85
- │ ├── app.py �� First FastAPI server
86
- │ └── README.md
87
- │
88
- ├── 🧬 step_02_medical_api/
89
- │ ├── app.py ← Real HuggingFace NER model
90
- │ └── README.md
91
- │
92
- ├── ⚡ step_03_live_model/
93
- │ ├── app.py ← Background jobs pattern
94
- │ └── README.md
95
- │
96
- ├── 🌐 step_04_deploy_render/
97
- │ ├── app.py ← Production-ready version
98
- │ ├── render.yaml ← One-click Render config
99
- │ └── README.md
100
- │
101
- ├── .devcontainer/
102
- │ └── devcontainer.json ← GitHub Codespaces config
103
- │
104
- └── requirements.txt ← All Python dependencies
105
- ```
106
-
107
- ---
108
-
109
- ## 🎯 Step-by-Step Guide
110
 
111
- ### [📖 Step 0 — Concepts](./step_00_concepts/README.md)
112
- *What IS an API? When should I use one? What's the lifecycle?*
113
-
114
- Start here if you want to understand the **why** before the **how**. Covers the key architectural decisions you'll face with ML models.
115
 
116
  ---
117
 
118
- ### [🚀 Step 1 — Hello API](./step_01_hello_api/README.md)
119
-
120
- ```bash
121
- cd step_01_hello_api
122
- uvicorn app:app --reload --port 8000
123
- ```
124
 
125
- Open `http://localhost:8000/docs` — you'll see your first auto-documented API. Try clicking every endpoint.
 
 
 
 
 
 
 
126
 
127
- **What you'll understand after this:** GET vs POST, URL parameters vs request body, Pydantic validation, the OpenAPI auto-docs.
128
 
129
  ---
130
 
131
- ### [🧬 Step 2 — Real Medical NLP](./step_02_medical_api/README.md)
132
 
133
- ```bash
134
- cd step_02_medical_api
135
- uvicorn app:app --reload --port 8000
136
- ```
137
 
138
- Send this to `/extract-entities`:
139
- ```json
140
- {
141
- "text": "Patient with acute myocardial infarction. On aspirin and metformin. BRCA1 positive.",
142
- "patient_id": "P001"
143
- }
144
- ```
145
-
146
- Get back:
147
- ```json
148
- {
149
- "entities": [
150
- {"entity_type": "Disease", "text": "myocardial infarction", "confidence": 0.98},
151
- {"entity_type": "Chemical", "text": "aspirin", "confidence": 0.96},
152
- {"entity_type": "Gene", "text": "BRCA1", "confidence": 0.93}
153
- ]
154
- }
155
- ```
156
-
157
- **What you'll understand after this:** Model loading strategy, zero-shot classification, the real answer to "how does the model run?"
158
-
159
- ---
160
 
161
- ### [⚡ Step 3 — Background Tasks](./step_03_live_model/README.md)
162
 
163
  ```bash
164
- cd step_03_live_model
165
- uvicorn app:app --reload --port 8000
166
- ```
167
-
168
- Submit a "slow" job and watch it process asynchronously. This is the pattern for pathology image analysis, large batch jobs, or any model that takes >5 seconds.
169
 
170
- **What you'll understand after this:** When NOT to use synchronous inference, how to build the submit→poll→retrieve pattern.
171
-
172
- ---
173
 
174
- ### [🌐 Step 4 — Deploy to Render](./step_04_deploy_render/README.md)
 
175
 
176
- Your API goes public. Render is free, connects directly to GitHub, and needs zero DevOps knowledge.
177
-
178
- **What you'll understand after this:** The full API lifecycle end-to-end, CORS for browser access, health checks, environment variables.
179
 
180
  ---
181
 
182
- ## 🌟 Bonus: Going Further
183
-
184
- Once you've completed the 4 steps, here are natural next directions:
185
 
186
- ### 🖥️ Add a Streamlit Frontend
187
- Let non-technical users interact with your API without knowing what an API is:
188
-
189
- ```bash
190
- # In a new terminal:
191
- streamlit run bonus/streamlit_frontend.py
192
- ```
193
-
194
- ### 📊 Try Different Medical Models
195
-
196
- | Model | Task | HuggingFace Link |
197
- |-------|------|-----------------|
198
- | `d4data/biomedical-ner-all` | NER: diseases, drugs, genes | [🔗](https://huggingface.co/d4data/biomedical-ner-all) |
199
- | `sultan/BioM-ELECTRA-Large-SQuAD2` | Medical Q&A | [🔗](https://huggingface.co/sultan/BioM-ELECTRA-Large-SQuAD2) |
200
- | `Falconsai/medical_summarization` | Note summarization | [🔗](https://huggingface.co/Falconsai/medical_summarization) |
201
- | `facebook/bart-large-mnli` | Zero-shot classification | [🔗](https://huggingface.co/facebook/bart-large-mnli) |
202
- | `allenai/longformer-base-4096` | Long clinical documents | [🔗](https://huggingface.co/allenai/longformer-base-4096) |
203
-
204
- ### 🏋️ Fine-Tune on Your Own Data
205
- Once you have labeled data, you can fine-tune any of these models:
206
- ```python
207
- from transformers import Trainer, TrainingArguments
208
- # Your data → better accuracy on your specific domain
209
  ```
210
-
211
- ### 🔐 Add Authentication
212
- For real clinical data, add API key authentication:
213
- ```python
214
- from fastapi.security import APIKeyHeader
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  ```
216
 
217
- ### 📈 Add Monitoring
218
- Track model performance over time with simple logging to a CSV or database.
219
-
220
  ---
221
 
222
- ## 🆘 Troubleshooting
223
 
224
- | Problem | Solution |
225
- |---------|---------|
226
- | `ModuleNotFoundError` | Run `pip install -r requirements.txt` |
227
- | Port 8000 already in use | `uvicorn app:app --port 8001` |
228
- | Model download is slow | Be patient (first time only, ~500MB). Or use demo mode by removing the transformers import. |
229
- | Render deploy fails | Check build logs for missing packages; add to `requirements.txt` |
230
- | CORS error from browser | Check CORS middleware in Step 4 — make sure your frontend URL is allowed |
 
 
 
 
 
 
 
 
231
 
232
  ---
233
 
234
- ## 📚 Reference Links
235
 
236
- | Resource | What it's for |
237
- |----------|-------------|
238
- | [FastAPI Docs](https://fastapi.tiangolo.com/) | Everything FastAPI |
239
- | [FastAPI in VS Code](https://code.visualstudio.com/docs/python/tutorial-fastapi) | IDE integration tips |
240
- | [Hugging Face Tutorial](https://youtu.be/QEaBAZQCtwE) | Video intro to HF models |
241
- | [Deploy NLP: FastAPI + Streamlit + HF Guide](https://towardsdatascience.com/deploy-nlp-models-with-fastapi-streamlit-and-hugging-face/) | Full stack deployment |
242
- | [Build FastAPI in Minutes](https://realpython.com/fastapi-python-web-apis/) | Quick reference |
243
- | [OpenAPI Specification](https://swagger.io/specification/) | Understanding auto-docs |
244
- | [Render Docs](https://render.com/docs) | Deployment platform |
245
 
246
  ---
247
 
248
- ## 💬 Learning Community
249
 
250
- Stuck? Have a question? Found a bug?
251
 
252
- - Open an **Issue** on this repo
253
- - Add your own experiment in a new branch and open a **Pull Request**
254
- - The best way to learn is to break things and ask why
 
 
 
 
 
 
 
 
255
 
256
  ---
257
 
258
- *Built for the medical research community. All models are for demonstration — not clinical use.*
 
1
+ # REST-API-Builder
 
2
 
3
+ A self-paced, hands-on tutorial that teaches you how to **build, test, and deploy a REST API** that serves a machine learning model — using healthcare examples throughout.
 
 
4
 
5
+ By the end, you will have a working API that classifies clinical notes as **urgent** or **routine**, tested with pytest, and deployed to the cloud.
 
 
 
 
 
 
 
 
 
6
 
7
  ---
 
 
 
8
 
9
+ ## Who Is This For?
10
 
11
+ Researchers and data scientists who:
12
+ - Have basic Python knowledge
13
+ - Have completed (or are familiar with) the [ci-cd-template](https://github.com/po-DRA/ci-cd-template) tutorial
14
+ - Want to learn how to serve ML models as REST APIs
15
+ - Are new to web APIs, HTTP, and deployment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  ---
18
 
19
+ ## What You'll Build
20
 
21
+ A **Clinical Urgency Prediction API** that:
22
+ 1. Accepts a clinical note (free text)
23
+ 2. Classifies it as `urgent` or `routine`
24
+ 3. Returns the prediction with a confidence score
25
+ 4. Stores predictions for later retrieval
26
+ 5. Is deployed and accessible via the internet
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  ---
29
 
30
+ ## Why a REST API (and Not Just pip install)?
31
 
32
+ | | **pip install (library)** | **REST API (service)** |
33
+ |---|---|---|
34
+ | **Users** | Python developers only | Anyone — any language, any device |
35
+ | **Setup** | Must install Python + all dependencies | Just needs HTTP (curl, browser, any language) |
36
+ | **Updates** | Every user must upgrade | Deploy once, everyone gets the new version |
37
+ | **Access control** | None | API keys, rate limits, audit logs |
38
+ | **Best for** | Reusable Python utilities | Serving predictions to apps, dashboards, teams |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ **Bottom line:** Use a library when consumers are Python devs who want full control. Use an API when you want *anyone* to use your model without installing anything.
 
 
 
41
 
42
  ---
43
 
44
+ ## Learning Path
 
 
 
 
 
45
 
46
+ | Lab | Topic | Time |
47
+ |---|---|---|
48
+ | [Lab 00](lab_00_rest_fundamentals/README.md) | REST Fundamentals — HTTP verbs, status codes, URL design | 30 min |
49
+ | [Lab 01](lab_01_your_first_api/README.md) | Your First API — FastAPI CRUD with all 5 HTTP verbs | 30 min |
50
+ | [Lab 02](lab_02_train_model/README.md) | Train the Model — TF-IDF + Logistic Regression pipeline | 20 min |
51
+ | [Lab 03](lab_03_expose_model/README.md) | Expose the Model — Serve predictions as a REST API | 30 min |
52
+ | [Lab 04](lab_04_test_api/README.md) | Test the API — pytest with FastAPI TestClient | 25 min |
53
+ | [Lab 05](lab_05_deploy/README.md) | Deploy — Render, HuggingFace Spaces, or Docker | 30 min |
54
 
55
+ **Total:** ~2.5 hours
56
 
57
  ---
58
 
59
+ ## Quick Start
60
 
61
+ ### Option 1: GitHub Codespaces (Recommended)
 
 
 
62
 
63
+ Click **Code → Codespaces → Create codespace on main**.
64
+ Everything is pre-configured via `.devcontainer/devcontainer.json`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ ### Option 2: Local Setup
67
 
68
  ```bash
69
+ # Clone the repo
70
+ git clone https://github.com/<your-username>/REST-API-Builder.git
71
+ cd REST-API-Builder
 
 
72
 
73
+ # Install uv (fast Python package manager) if you don't have it
74
+ pip install uv
 
75
 
76
+ # Install all dependencies (creates a .venv automatically)
77
+ uv sync --extra dev
78
 
79
+ # Start with Lab 00!
80
+ ```
 
81
 
82
  ---
83
 
84
+ ## Folder Structure
 
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  ```
87
+ REST-API-Builder/
88
+ ├── README.md ← You are here
89
+ ├── pyproject.toml ← Dependencies, tool config (ruff, pytest)
90
+ ├── render.yaml ← Render deployment config
91
+ ├── Dockerfile ← Docker / HuggingFace Spaces config
92
+ ├── .gitignore
93
+ ├── .devcontainer/
94
+ │ └── devcontainer.json ← Codespaces / Dev Container config
95
+ ├── data/
96
+ │ └── clinical_notes.csv ← 30 labelled clinical notes
97
+ ├── models/
98
+ │ └── README.md ← Generated model files go here
99
+ ├── solutions/
100
+ │ ├── lab_00_answers.md ← Quiz answers for Lab 00
101
+ │ └── lab_01_challenge3.md ← Solution for Lab 01 stretch challenge
102
+ ├── lab_00_rest_fundamentals/
103
+ │ └── README.md ← REST theory + quiz
104
+ ├── lab_01_your_first_api/
105
+ │ ├── app.py ← FastAPI CRUD server
106
+ │ └── README.md
107
+ ├── lab_02_train_model/
108
+ │ ├── train.py ← Train the urgency classifier
109
+ │ └── README.md
110
+ ├── lab_03_expose_model/
111
+ │ ├── app.py ← ML model as REST API
112
+ │ └── README.md
113
+ ├── lab_04_test_api/
114
+ │ ├── test_api.py ← pytest tests
115
+ │ └── README.md
116
+ └── lab_05_deploy/
117
+ ├── app.py ← Production-ready app
118
+ └── README.md
119
  ```
120
 
 
 
 
121
  ---
122
 
123
+ ## Reference Materials
124
 
125
+ These resources are linked throughout the labs:
126
+
127
+ | Resource | Link |
128
+ |---|---|
129
+ | REST API Cheatsheet | [ByteByteGo](https://bytebytego.com/guides/rest-api-cheatsheet/) |
130
+ | API Learning Roadmap | [ByteByteGo](https://bytebytego.com/guides/the-ultimate-api-learning-roadmap/) |
131
+ | What is an API | [IBM](https://www.ibm.com/topics/api) |
132
+ | API Lifecycle | [IBM](https://www.ibm.com/think/topics/api-lifecycle) |
133
+ | OpenAPI Intro | [Swagger](https://swagger.io/docs/specification/about/) |
134
+ | OpenAPI Specification | [Swagger](https://swagger.io/specification/) |
135
+ | FastAPI Docs | [fastapi.tiangolo.com](https://fastapi.tiangolo.com/) |
136
+ | Deploying ML with FastAPI | [Analytics Vidhya](https://www.analyticsvidhya.com/blog/2022/09/deploying-ml-models-using-fastapi/) |
137
+ | FastAPI + HuggingFace | [Towards Data Science](https://towardsdatascience.com/deploy-nlp-models-with-fastapi-streamlit-and-hugging-face/) |
138
+ | Build FastAPI in Minutes | [Real Python](https://realpython.com/fastapi-python-web-apis/) |
139
+ | Training Script Inspiration | [ci-cd-template](https://github.com/po-DRA/ci-cd-template/blob/main/scripts/train.py) |
140
 
141
  ---
142
 
143
+ ## License
144
 
145
+ This tutorial is for educational purposes. Use it, adapt it, share it.
 
 
 
 
 
 
 
 
146
 
147
  ---
148
 
149
+ ## Citation
150
 
151
+ If you use this template for teaching, research, or derivative work, please cite it:
152
 
153
+ ```bibtex
154
+ @software{ojha_rest_api_builder,
155
+ author = {Ojha, Priyanka},
156
+ orcid = {https://orcid.org/0000-0002-6844-6493},
157
+ title = {REST-API-Builder: Hands-on REST API Tutorial for ML},
158
+ url = {https://github.com/po-DRA/REST-API-Builder},
159
+ version = {1.0.0},
160
+ year = {2026},
161
+ license = {MIT}
162
+ }
163
+ ```
164
 
165
  ---
166
 
167
+ Made with help of Claude and tested by a real human.
data/clinical_notes.csv ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ note,label
2
+ "Patient presents with acute chest pain radiating to left arm, diaphoresis, and shortness of breath. ECG shows ST-elevation in leads II, III, and aVF. Troponin elevated at 2.4 ng/mL.",urgent
3
+ "Severe hypotension with systolic BP 70 mmHg. Patient is tachycardic at 130 bpm. Suspected septic shock secondary to urinary tract infection. Immediate IV fluid resuscitation initiated.",urgent
4
+ "Patient found unresponsive with GCS of 5. CT head reveals large intracerebral hemorrhage with midline shift. Neurosurgery consult requested emergently.",urgent
5
+ "Acute respiratory distress with SpO2 78% on room air. Bilateral crackles on auscultation. Chest X-ray shows diffuse bilateral infiltrates consistent with ARDS. Intubation being prepared.",urgent
6
+ "New onset atrial fibrillation with rapid ventricular response at 180 bpm. Patient complaining of palpitations and dizziness. Hemodynamically unstable.",urgent
7
+ "Suspected pulmonary embolism with acute onset dyspnea and pleuritic chest pain. D-dimer elevated at 4500 ng/mL. CT angiography ordered stat.",urgent
8
+ "Patient presenting with signs of diabetic ketoacidosis. Blood glucose 580 mg/dL, pH 7.1, bicarbonate 8 mEq/L. Insulin drip protocol initiated.",urgent
9
+ "Acute abdomen with rebound tenderness and guarding. CT shows perforated appendix with free air. Surgical team notified for emergency laparotomy.",urgent
10
+ "Status epilepticus lasting over 30 minutes. IV lorazepam administered without effect. Second-line agent levetiracetam being loaded. EEG monitoring initiated.",urgent
11
+ "Massive upper GI hemorrhage with hematemesis. Hemoglobin dropped from 12 to 6.5 g/dL in 4 hours. Emergent endoscopy and transfusion of 4 units pRBC ordered.",urgent
12
+ "Patient here for routine annual physical examination. No acute complaints. Blood pressure 122/78, BMI 24. Due for colorectal cancer screening.",routine
13
+ "Follow-up visit for well-controlled type 2 diabetes. HbA1c stable at 6.8%. Patient tolerating metformin well. Continue current regimen and recheck in 3 months.",routine
14
+ "Routine post-operative follow-up 6 weeks after total knee replacement. Wound healed well. Range of motion improving with physical therapy. No signs of infection.",routine
15
+ "Patient presents for annual dermatology skin check. No new or changing moles identified. Counseled on sun protection and scheduled next annual visit.",routine
16
+ "Well-child visit for 8-year-old. Growth and development on track. Immunizations up to date. Vision and hearing screening normal.",routine
17
+ "Routine prenatal visit at 28 weeks gestation. Fetal heart rate 145 bpm. Fundal height appropriate. Glucose tolerance test results within normal limits.",routine
18
+ "Follow-up for mild seasonal allergies. Symptoms controlled with over-the-counter cetirizine. No new medications needed. Return as needed.",routine
19
+ "Patient requesting medication refill for stable hypertension. Blood pressure well controlled at 128/82 on lisinopril 10mg daily. Labs from last month all within normal limits.",routine
20
+ "Routine colonoscopy screening in 55-year-old patient. No family history of colorectal cancer. Pre-procedure assessment completed. Scheduled for next available date.",routine
21
+ "Follow-up for chronic low back pain managed with physical therapy and NSAIDs. Patient reports 50% improvement in symptoms. Continue current management plan.",routine
22
+ "Annual ophthalmology exam for diabetic retinopathy screening. No evidence of retinopathy. Visual acuity 20/25 bilateral. Recheck in 12 months.",routine
23
+ "Patient presents for routine lab work prior to medication renewal. Currently on statin therapy for hyperlipidemia. Fasting lipid panel and liver function tests ordered.",routine
24
+ "Post-discharge follow-up after uncomplicated pneumonia treated with oral antibiotics. Symptoms fully resolved. Chest X-ray shows clearing infiltrate. No further treatment needed.",routine
25
+ "Routine mental health follow-up. Patient stable on current SSRI regimen. PHQ-9 score improved from 12 to 5. Continue sertraline 50mg daily.",routine
26
+ "Pre-employment physical examination. Patient in good overall health. No significant medical history. Cleared for full duty work without restrictions.",routine
27
+ "Follow-up for iron deficiency anemia. Ferritin improved from 8 to 35 ng/mL with oral iron supplementation. Continue supplementation for 3 more months and recheck.",routine
28
+ "Routine 6-month dental referral follow-up. No oral health concerns. Gingivitis resolved with improved hygiene. Next dental visit in 6 months.",routine
29
+ "Patient here for travel medicine consultation ahead of trip to Southeast Asia. Vaccines reviewed and updated. Antimalarial prophylaxis prescribed.",routine
30
+ "Follow-up visit for managed hypothyroidism. TSH 2.1 mIU/L on levothyroxine 75mcg daily. Patient reports normal energy levels. Continue current dose.",routine
31
+ "Annual gynecological exam. Pap smear collected. Breast exam unremarkable. Discussed contraceptive options. Results to be communicated within 2 weeks.",routine
32
+ "Acute anaphylaxis after penicillin administration. Widespread urticaria, angioedema, and stridor. Epinephrine 0.3mg IM administered. Crash cart at bedside.",urgent
33
+ "Tension pneumothorax suspected. Absent breath sounds on left with tracheal deviation to right. Needle decompression being performed at second intercostal space.",urgent
34
+ "Acute stroke symptoms with right-sided hemiplegia and expressive aphasia. Onset 45 minutes ago. CT head negative for hemorrhage. tPA eligibility being assessed.",urgent
35
+ "Ruptured ectopic pregnancy with acute abdomen and hemodynamic instability. Positive pregnancy test with free fluid on ultrasound. Emergency surgery required.",urgent
36
+ "Severe burn injury covering 40% total body surface area. Second and third degree burns to torso and extremities. Fluid resuscitation per Parkland formula initiated.",urgent
lab_00_rest_fundamentals/README.md ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 00 — REST Fundamentals
2
+
3
+ > **Goal:** Understand what REST is, how HTTP works, and why these ideas
4
+ > matter before you write a single line of API code.
5
+
6
+ > **Time:** ~30 minutes of reading + quiz
7
+
8
+ ---
9
+
10
+ ## Why Should a Researcher Care About APIs?
11
+
12
+ Imagine you have trained a brilliant model that predicts clinical urgency
13
+ from free-text notes. Right now it lives inside a Jupyter notebook on
14
+ your laptop. To let **anyone else** use it — a colleague, a dashboard,
15
+ a mobile app, another service — you need to wrap it in an **API**
16
+ (Application Programming Interface).
17
+
18
+ > 📖 Read more: [What is an API? (IBM)](https://www.ibm.com/topics/api)
19
+
20
+ ### API vs. pip install — When to Use Which
21
+
22
+ | | **pip install (library)** | **REST API (service)** |
23
+ |---|---|---|
24
+ | **Who uses it** | Python developers only | Anyone — Python, JavaScript, mobile apps, curl |
25
+ | **Where it runs** | On the caller's machine | On a server you control |
26
+ | **Dependencies** | Caller must install everything (scikit-learn, pandas…) | Caller needs only HTTP — zero setup |
27
+ | **Updates** | Every user must `pip install --upgrade` | You deploy once; everyone gets the new version instantly |
28
+ | **Access control** | None — anyone with the package can use it | You can add API keys, rate limits, logging |
29
+ | **Data privacy** | Data stays on the caller's machine | Data is sent to your server (you control security) |
30
+ | **Best for** | Reusable utilities, offline analysis | Serving predictions, dashboards, cross-language integrations |
31
+
32
+ **Rule of thumb:**
33
+ - Use a **library** when the consumer is a Python developer who wants full control.
34
+ - Use an **API** when you want *anyone* (any language, any device) to use your model
35
+ without installing anything.
36
+
37
+ In healthcare, APIs are especially useful: you can put the model behind
38
+ authentication, log every prediction for auditing, and update the model
39
+ without asking every clinical team to reinstall software.
40
+
41
+ ---
42
+
43
+ ## The 6 REST Principles (in Plain English)
44
+
45
+ REST stands for **RE**presentational **S**tate **T**ransfer. It is not a
46
+ protocol or a library — it is a set of *architectural principles* that
47
+ make APIs predictable, scalable, and easy to use.
48
+
49
+ > 📖 Keep the [ByteByteGo REST API Cheatsheet](https://bytebytego.com/guides/rest-api-cheatsheet/)
50
+ > open as you read — it's a great visual companion.
51
+
52
+ ### 1. Client–Server Separation
53
+
54
+ The **client** (e.g. a React dashboard) and the **server** (your
55
+ FastAPI app) are independent. The client doesn't know how the model
56
+ was trained; the server doesn't know whether the client is a phone or
57
+ a laptop.
58
+
59
+ *Healthcare example:* An EHR system (client) sends a clinical note to
60
+ your prediction API (server). Neither cares about the other's tech
61
+ stack.
62
+
63
+ ### 2. Statelessness
64
+
65
+ Every request from the client must contain **all the information** the
66
+ server needs. The server does not remember previous requests.
67
+
68
+ *Why this matters:* If a nurse sends two prediction requests, the
69
+ server doesn't need to remember the first one to handle the second.
70
+ This makes scaling easy — you can run 10 copies of the server and any
71
+ copy can handle any request.
72
+
73
+ ### 3. Cacheability
74
+
75
+ Responses should say whether they can be cached. A `GET` request for
76
+ patient demographics changes rarely and is safe to cache. A `POST`
77
+ that creates a new prediction is not.
78
+
79
+ ### 4. Uniform Interface
80
+
81
+ Every REST API uses the same HTTP verbs (`GET`, `POST`, etc.) and the
82
+ same URL conventions. Once you learn one REST API, you can use any
83
+ REST API.
84
+
85
+ ### 5. Layered System
86
+
87
+ Between the client and server there can be load balancers, caches,
88
+ authentication proxies — the client doesn't know or care.
89
+
90
+ ### 6. Code on Demand (optional)
91
+
92
+ The server *can* send executable code (like JavaScript) to the client.
93
+ This is rarely used in data-science APIs, so don't worry about it.
94
+
95
+ ---
96
+
97
+ ## HTTP Verbs — The 5 Actions You Can Take
98
+
99
+ Think of a REST API as a filing cabinet. The **URL** tells you *which
100
+ drawer* (resource) you want. The **HTTP verb** tells you *what you
101
+ want to do* with it.
102
+
103
+ > 📖 See these verbs in context on the
104
+ > [ByteByteGo REST API Cheatsheet](https://bytebytego.com/guides/rest-api-cheatsheet/).
105
+
106
+ | Verb | What It Does | Medical Example | Typical Success Code |
107
+ |---|---|---|---|
108
+ | **GET** | Read / retrieve data | Get a patient's lab results | `200 OK` |
109
+ | **POST** | Create a new resource | Submit a new clinical note for prediction | `201 Created` |
110
+ | **PUT** | Replace a resource entirely | Replace a patient's full allergy profile | `200 OK` |
111
+ | **PATCH** | Update part of a resource | Change just the phone number on a patient record | `200 OK` |
112
+ | **DELETE** | Remove a resource | Remove a cancelled appointment | `204 No Content` |
113
+
114
+ ### Key distinctions
115
+
116
+ - **POST vs. PUT:** POST *creates* something new (the server assigns an
117
+ ID). PUT *replaces* an existing item (the client knows the ID).
118
+ - **PUT vs. PATCH:** PUT sends the *complete* new version. PATCH sends
119
+ only the fields that changed.
120
+ - **DELETE returns 204** — this means "success, but there is nothing to
121
+ send back" (the thing is gone!).
122
+
123
+ ---
124
+
125
+ ## HTTP Status Codes — What the Server Tells You
126
+
127
+ Status codes are the server's way of saying what happened. They are
128
+ grouped by the first digit:
129
+
130
+ | Range | Meaning | Think of it as… |
131
+ |---|---|---|
132
+ | **2xx** | ✅ Success | "All good!" |
133
+ | **4xx** | ❌ Client error | "You did something wrong." |
134
+ | **5xx** | 💥 Server error | "We messed up." |
135
+
136
+ ### The codes you'll use most often
137
+
138
+ | Code | Name | When to Use It | Example |
139
+ |---|---|---|---|
140
+ | `200` | OK | Successful GET, PUT, or PATCH | `GET /v1/patients/42` → returns patient data |
141
+ | `201` | Created | Successful POST that created something | `POST /v1/predictions` → new prediction stored |
142
+ | `204` | No Content | Successful DELETE (nothing to return) | `DELETE /v1/predictions/7` → prediction removed |
143
+ | `400` | Bad Request | Request is malformed or missing fields | Sending JSON without a required `note` field |
144
+ | `401` | Unauthorized | No credentials provided | Calling the API without an API key |
145
+ | `403` | Forbidden | Credentials valid, but not enough permission | A read-only user trying to DELETE |
146
+ | `404` | Not Found | The resource doesn't exist | `GET /v1/patients/99999` — no such patient |
147
+ | `422` | Unprocessable Entity | JSON is valid but values are wrong | `{"age": -5}` — age can't be negative |
148
+ | `500` | Internal Server Error | Bug in the server code | Unhandled exception in your Python code |
149
+ | `503` | Service Unavailable | Server is overloaded or down | Model file missing; API can't serve predictions |
150
+
151
+ > 📖 Bookmark the full list:
152
+ > [ByteByteGo REST API Cheatsheet](https://bytebytego.com/guides/rest-api-cheatsheet/)
153
+
154
+ ---
155
+
156
+ ## REST URL Design Rules
157
+
158
+ Good URLs are **predictable** and **readable**. Follow these rules:
159
+
160
+ ### 1. Use nouns, not verbs
161
+
162
+ ```
163
+ ✅ GET /v1/patients ← "get me the list of patients"
164
+ ❌ GET /v1/getPatients ← the verb is already in the HTTP method!
165
+ ```
166
+
167
+ ### 2. Use plurals for collections
168
+
169
+ ```
170
+ ✅ /v1/patients
171
+ ❌ /v1/patient
172
+ ```
173
+
174
+ ### 3. Version your API
175
+
176
+ Put the version in the URL so you can evolve without breaking old clients:
177
+
178
+ ```
179
+ /v1/patients ← version 1
180
+ /v2/patients ← version 2, maybe different response format
181
+ ```
182
+
183
+ ### 4. Use path parameters for specific resources
184
+
185
+ ```
186
+ GET /v1/patients/42 ← patient with ID 42
187
+ DELETE /v1/predictions/abc ← prediction with ID abc
188
+ ```
189
+
190
+ ### 5. Use query parameters for filtering, sorting, and pagination
191
+
192
+ ```
193
+ GET /v1/patients?status=active&limit=10&offset=0
194
+ ^^^^^^^^ ^^^^^ ^^^^^^
195
+ filter page skip
196
+ size count
197
+ ```
198
+
199
+ ---
200
+
201
+ ## Path Parameters vs. Query Parameters
202
+
203
+ This is a common point of confusion. Here's the simple rule:
204
+
205
+ | Type | Where It Goes | Purpose | Example |
206
+ |---|---|---|---|
207
+ | **Path parameter** | Inside the URL path | Identify a *specific* resource | `/v1/patients/42` |
208
+ | **Query parameter** | After the `?` | Filter, sort, or paginate a *collection* | `/v1/patients?status=active` |
209
+
210
+ **In plain English:**
211
+ - Path params answer: **"Which one?"**
212
+ - Query params answer: **"Which subset? How many? In what order?"**
213
+
214
+ ---
215
+
216
+ ## The API Lifecycle
217
+
218
+ Before building, it helps to understand the typical stages an API goes through:
219
+
220
+ 1. **Design** — Define endpoints, request/response shapes (OpenAPI spec)
221
+ 2. **Build** — Implement with a framework like FastAPI
222
+ 3. **Test** — Automated tests with pytest
223
+ 4. **Deploy** — Ship to Render, HuggingFace Spaces, or Docker
224
+ 5. **Monitor** — Track usage, errors, latency
225
+ 6. **Iterate** — Version and improve
226
+
227
+ > 📖 Deep dive: [API Lifecycle (IBM)](https://www.ibm.com/think/topics/api-lifecycle)
228
+ >
229
+ > 📖 Learning path: [The Ultimate API Learning Roadmap (ByteByteGo)](https://bytebytego.com/guides/the-ultimate-api-learning-roadmap/)
230
+
231
+ ---
232
+
233
+ ## The OpenAPI Specification (Bonus)
234
+
235
+ FastAPI **automatically** generates an OpenAPI spec for your API.
236
+ OpenAPI is a standard way to describe your endpoints so that tools can
237
+ generate documentation, client libraries, and tests.
238
+
239
+ When you run a FastAPI server, visit:
240
+ - `/docs` — interactive Swagger UI (try endpoints in the browser!)
241
+ - `/redoc` — clean, readable docs
242
+ - `/openapi.json` — the raw spec
243
+
244
+ > 📖 More about OpenAPI:
245
+ > [About OpenAPI (Swagger)](https://swagger.io/docs/specification/about/) |
246
+ > [OpenAPI Specification](https://swagger.io/specification/)
247
+
248
+ ---
249
+
250
+ ## 📝 Quiz — Test Your Understanding
251
+
252
+ Answer these questions, then check your answers in
253
+ [solutions/lab_00_answers.md](../solutions/lab_00_answers.md).
254
+
255
+ 1. You want to retrieve a list of all patients. Which HTTP verb do you use?
256
+ 2. You create a new prediction. What status code should the server return?
257
+ 3. You delete prediction #7. What status code should the server return?
258
+ 4. What is wrong with this URL: `GET /v1/getActivePatients`?
259
+ 5. A client sends `GET /v1/patients/99999` but that patient doesn't exist.
260
+ What status code should the server return?
261
+ 6. What is the difference between a path parameter and a query parameter?
262
+ Give an example of each.
263
+ 7. Why is statelessness important for scaling an API?
264
+ 8. Your colleague says "just pip install my model." Give two reasons
265
+ why wrapping it in a REST API might be a better choice.
266
+ 9. What does a `422 Unprocessable Entity` status code mean?
267
+ 10. Name two things FastAPI auto-generates from the OpenAPI spec.
268
+
269
+ ---
270
+
271
+ ## ✅ Done When
272
+
273
+ - [ ] You can name all 5 HTTP verbs and when to use each
274
+ - [ ] You know the difference between 200, 201, and 204
275
+ - [ ] You understand path params vs. query params
276
+ - [ ] You can explain why a REST API is better than `pip install` for
277
+ serving a model to non-Python users
278
+ - [ ] You completed the quiz and checked your answers
279
+
280
+ ---
281
+
282
+ **Next →** [Lab 01: Your First API](../lab_01_your_first_api/README.md)
lab_01_your_first_api/README.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 01 — Your First REST API
2
+
3
+ > **Goal:** Build a working FastAPI server that manages patients using
4
+ > all 5 HTTP verbs, with correct REST status codes.
5
+
6
+ > **Time:** ~30 minutes
7
+
8
+ > **Prerequisites:** [Lab 00 — REST Fundamentals](../lab_00_rest_fundamentals/README.md)
9
+
10
+ ---
11
+
12
+ ## What You'll Learn
13
+
14
+ - How to create a FastAPI application
15
+ - How to implement GET, POST, PUT, PATCH, and DELETE
16
+ - How to use path parameters and query parameters
17
+ - How to return the correct HTTP status codes
18
+ - How Pydantic validates input automatically
19
+
20
+ ---
21
+
22
+ ## Setup
23
+
24
+ ```bash
25
+ # Make sure you've installed dependencies
26
+ uv sync --extra dev
27
+
28
+ # Run the server (from the project root)
29
+ cd lab_01_your_first_api
30
+ uvicorn app:app --reload
31
+ ```
32
+
33
+ The `--reload` flag restarts the server whenever you save a change —
34
+ perfect for development.
35
+
36
+ ---
37
+
38
+ ## Explore the API
39
+
40
+ Once the server is running, open these URLs in your browser:
41
+
42
+ | URL | What It Shows |
43
+ |---|---|
44
+ | http://127.0.0.1:8000/docs | Interactive Swagger UI — try every endpoint! |
45
+ | http://127.0.0.1:8000/redoc | Clean, readable API documentation |
46
+ | http://127.0.0.1:8000/v1/patients | JSON list of all patients |
47
+
48
+ > **Tip:** The Swagger UI at `/docs` lets you click "Try it out" on any
49
+ > endpoint and send real requests. This is one of the best features of
50
+ > FastAPI — you get interactive docs for free.
51
+
52
+ ---
53
+
54
+ ## Try These Requests
55
+
56
+ You can use the Swagger UI, `curl`, or any HTTP client (Thunder Client
57
+ in VS Code is great).
58
+
59
+ ### List all patients
60
+ ```bash
61
+ curl http://127.0.0.1:8000/v1/patients
62
+ ```
63
+
64
+ ### Filter by condition
65
+ ```bash
66
+ curl "http://127.0.0.1:8000/v1/patients?condition=asthma"
67
+ ```
68
+
69
+ ### Create a new patient
70
+ ```bash
71
+ curl -X POST http://127.0.0.1:8000/v1/patients \
72
+ -H "Content-Type: application/json" \
73
+ -d '{"name": "David Lee", "age": 65, "condition": "COPD"}'
74
+ ```
75
+ Notice the response is `201 Created` — not `200 OK`.
76
+
77
+ ### Get a specific patient (use an ID from the list)
78
+ ```bash
79
+ curl http://127.0.0.1:8000/v1/patients/<paste-id-here>
80
+ ```
81
+
82
+ ### Delete a patient
83
+ ```bash
84
+ curl -X DELETE http://127.0.0.1:8000/v1/patients/<paste-id-here>
85
+ ```
86
+ Notice the response is `204 No Content` — the patient is gone, nothing
87
+ to return.
88
+
89
+ ### Try a patient that doesn't exist
90
+ ```bash
91
+ curl http://127.0.0.1:8000/v1/patients/nonexistent-id
92
+ ```
93
+ You should get `404 Not Found`.
94
+
95
+ ---
96
+
97
+ ## Code Walkthrough
98
+
99
+ Open [app.py](app.py) and read through the comments. Key things to
100
+ notice:
101
+
102
+ 1. **Every endpoint has the correct status code** — `201` for POST,
103
+ `204` for DELETE, `404` for missing resources.
104
+ 2. **Pydantic models validate input** — if someone sends `{"age": -5}`,
105
+ FastAPI returns `422` automatically.
106
+ 3. **Query params handle filtering and pagination** — the list endpoint
107
+ supports `?condition=X&limit=10&offset=0`.
108
+ 4. **Path params identify specific resources** — `/v1/patients/{id}`.
109
+ 5. **Response envelope** — every response uses `{data: ..., meta: ...}`
110
+ for consistency.
111
+
112
+ ---
113
+
114
+ ## 🎯 Challenges
115
+
116
+ See the YOUR TURN section at the bottom of [app.py](app.py):
117
+
118
+ 1. **(Easy)** Add a `GET /v1/patients/count` endpoint
119
+ 2. **(Medium)** Add a `min_age` query parameter to the list endpoint
120
+ 3. **(Stretch)** Add a `POST /v1/patients/search` endpoint — see
121
+ [solutions/lab_01_challenge3.md](../solutions/lab_01_challenge3.md)
122
+
123
+ ---
124
+
125
+ ## ✅ Done When
126
+
127
+ - [ ] Your server is running and you can see the Swagger docs at `/docs`
128
+ - [ ] You have tried all 5 HTTP verbs (GET, POST, PUT, PATCH, DELETE)
129
+ - [ ] You got a `201` from POST, `204` from DELETE, `404` from a missing ID
130
+ - [ ] You understand the difference between path params and query params
131
+ - [ ] You attempted at least one challenge
132
+
133
+ ---
134
+
135
+ **Next →** [Lab 02: Train the Model](../lab_02_train_model/README.md)
lab_01_your_first_api/app.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lab 01 — Your First REST API
3
+ =============================
4
+ A working FastAPI server that manages a /v1/patients resource,
5
+ demonstrating all 5 HTTP verbs with correct REST status codes.
6
+
7
+ How to run:
8
+ cd lab_01_your_first_api
9
+ uvicorn app:app --reload
10
+
11
+ Then open http://127.0.0.1:8000/docs to explore the interactive docs.
12
+
13
+ Reference:
14
+ - FastAPI docs: https://fastapi.tiangolo.com/
15
+ - Build a FastAPI in minutes: https://realpython.com/fastapi-python-web-apis/
16
+ - REST cheatsheet: https://bytebytego.com/guides/rest-api-cheatsheet/
17
+ """
18
+
19
+ from uuid import uuid4
20
+
21
+ from fastapi import FastAPI, HTTPException, Query
22
+ from pydantic import BaseModel, Field
23
+
24
+ # ── Create the FastAPI application ──────────────────────────────────
25
+ # metadata shows up in the auto-generated docs at /docs
26
+ app = FastAPI(
27
+ title="Patient Management API",
28
+ description="Lab 01 — Learn REST verbs with a healthcare example",
29
+ version="1.0.0",
30
+ )
31
+
32
+ # ── Data model ──────────────────────────────────────────────────────
33
+ # Pydantic models validate incoming JSON automatically.
34
+ # If someone sends {"age": "banana"}, FastAPI returns 422 for us.
35
+
36
+
37
+ class PatientCreate(BaseModel):
38
+ """Fields required when CREATING a new patient (POST)."""
39
+
40
+ name: str = Field(..., examples=["Jane Doe"])
41
+ age: int = Field(..., ge=0, le=150, examples=[45])
42
+ condition: str = Field(..., examples=["hypertension"])
43
+
44
+
45
+ class PatientUpdate(BaseModel):
46
+ """Fields for a FULL replacement (PUT) — all fields required."""
47
+
48
+ name: str = Field(..., examples=["Jane Doe"])
49
+ age: int = Field(..., ge=0, le=150, examples=[46])
50
+ condition: str = Field(..., examples=["diabetes"])
51
+
52
+
53
+ class PatientPatch(BaseModel):
54
+ """Fields for a PARTIAL update (PATCH) — every field is optional."""
55
+
56
+ name: str | None = None
57
+ age: int | None = Field(None, ge=0, le=150)
58
+ condition: str | None = None
59
+
60
+
61
+ # ── In-memory "database" ───────────────────────────────────────────
62
+ # In a real app this would be PostgreSQL, MongoDB, etc.
63
+ # We use a dict so every verb (GET, POST, PUT, PATCH, DELETE) works.
64
+ patients_db: dict[str, dict] = {}
65
+
66
+
67
+ # ── Seed some sample data ──────────────────────────────────────────
68
+ # This makes the API more interesting to explore right away.
69
+ _seed = [
70
+ {"name": "Alice Smith", "age": 34, "condition": "asthma"},
71
+ {"name": "Bob Johnson", "age": 72, "condition": "atrial fibrillation"},
72
+ {"name": "Carol Williams", "age": 58, "condition": "type 2 diabetes"},
73
+ ]
74
+ for _p in _seed:
75
+ _id = str(uuid4())
76
+ patients_db[_id] = {"id": _id, **_p}
77
+
78
+
79
+ # =====================================================================
80
+ # GET /v1/patients — List all patients (with filtering & pagination)
81
+ # =====================================================================
82
+ # GET is for READING data. It should NEVER modify anything on the server.
83
+ # We return 200 OK because the request succeeded.
84
+
85
+
86
+ @app.get("/v1/patients", status_code=200, tags=["Patients"])
87
+ def list_patients(
88
+ # Query parameters let clients filter and paginate.
89
+ # Example: GET /v1/patients?condition=asthma&limit=5&offset=0
90
+ condition: str | None = Query(None, description="Filter by medical condition"),
91
+ limit: int = Query(10, ge=1, le=100, description="Max results to return"),
92
+ offset: int = Query(0, ge=0, description="Number of results to skip"),
93
+ ):
94
+ """
95
+ List patients with optional filtering and pagination.
96
+
97
+ REST notes:
98
+ - Uses GET because we are READING, not creating or modifying.
99
+ - Query params (?condition=X) filter the collection.
100
+ - limit/offset implement pagination so clients don't get 1 million
101
+ records at once.
102
+ """
103
+ results = list(patients_db.values())
104
+
105
+ # Apply filter if the client sent ?condition=something
106
+ if condition:
107
+ results = [p for p in results if p["condition"].lower() == condition.lower()]
108
+
109
+ # Total count BEFORE pagination (useful for the client to know how
110
+ # many pages there are)
111
+ total = len(results)
112
+
113
+ # Slice for pagination
114
+ results = results[offset : offset + limit]
115
+
116
+ # Return a consistent response envelope: {data: [...], meta: {...}}
117
+ return {
118
+ "data": results,
119
+ "meta": {"total": total, "limit": limit, "offset": offset},
120
+ }
121
+
122
+
123
+ # =====================================================================
124
+ # GET /v1/patients/{patient_id} — Get one patient by ID
125
+ # =====================================================================
126
+ # The {patient_id} in the URL is a PATH PARAMETER.
127
+ # Path params identify a SPECIFIC resource (answer: "which one?").
128
+
129
+
130
+ @app.get("/v1/patients/{patient_id}", status_code=200, tags=["Patients"])
131
+ def get_patient(patient_id: str):
132
+ """
133
+ Retrieve a single patient by ID.
134
+
135
+ REST notes:
136
+ - Path parameter identifies the specific resource.
137
+ - Returns 404 if the patient does not exist — this is the correct
138
+ REST response for "resource not found".
139
+ """
140
+ if patient_id not in patients_db:
141
+ # 404 = "I understood your request, but that thing doesn't exist."
142
+ raise HTTPException(status_code=404, detail="Patient not found")
143
+ return {"data": patients_db[patient_id]}
144
+
145
+
146
+ # =====================================================================
147
+ # POST /v1/patients — Create a new patient
148
+ # =====================================================================
149
+ # POST means "create a new resource". The server assigns the ID.
150
+ # We return 201 Created (NOT 200) because something new was created.
151
+
152
+
153
+ @app.post("/v1/patients", status_code=201, tags=["Patients"])
154
+ def create_patient(patient: PatientCreate):
155
+ """
156
+ Create a new patient record.
157
+
158
+ REST notes:
159
+ - POST creates a NEW resource. The server generates the ID.
160
+ - Returns 201 Created with the new resource in the body.
161
+ - If the client sends invalid data (e.g. age = -5), FastAPI
162
+ automatically returns 422 Unprocessable Entity.
163
+ """
164
+ patient_id = str(uuid4())
165
+ record = {"id": patient_id, **patient.model_dump()}
166
+ patients_db[patient_id] = record
167
+ return {"data": record}
168
+
169
+
170
+ # =====================================================================
171
+ # PUT /v1/patients/{patient_id} — Replace a patient entirely
172
+ # =====================================================================
173
+ # PUT means "replace the entire resource with this new version".
174
+ # The client must send ALL fields, not just the ones that changed.
175
+
176
+
177
+ @app.put("/v1/patients/{patient_id}", status_code=200, tags=["Patients"])
178
+ def replace_patient(patient_id: str, patient: PatientUpdate):
179
+ """
180
+ Replace a patient record entirely.
181
+
182
+ REST notes:
183
+ - PUT replaces the WHOLE resource. Every field must be provided.
184
+ - Returns 404 if the patient doesn't exist.
185
+ - Returns 200 with the updated resource.
186
+ """
187
+ if patient_id not in patients_db:
188
+ raise HTTPException(status_code=404, detail="Patient not found")
189
+
190
+ record = {"id": patient_id, **patient.model_dump()}
191
+ patients_db[patient_id] = record
192
+ return {"data": record}
193
+
194
+
195
+ # =====================================================================
196
+ # PATCH /v1/patients/{patient_id} — Update part of a patient
197
+ # =====================================================================
198
+ # PATCH means "update only the fields I'm sending".
199
+ # Unlike PUT, you don't have to resend the entire object.
200
+
201
+
202
+ @app.patch("/v1/patients/{patient_id}", status_code=200, tags=["Patients"])
203
+ def update_patient(patient_id: str, updates: PatientPatch):
204
+ """
205
+ Partially update a patient record.
206
+
207
+ REST notes:
208
+ - PATCH updates only the provided fields (partial update).
209
+ - PUT would require ALL fields (full replacement).
210
+ - Use PATCH when the client only knows one field changed.
211
+ """
212
+ if patient_id not in patients_db:
213
+ raise HTTPException(status_code=404, detail="Patient not found")
214
+
215
+ existing = patients_db[patient_id]
216
+
217
+ # model_dump(exclude_unset=True) gives us ONLY the fields the
218
+ # client actually sent, ignoring fields left as None.
219
+ patch_data = updates.model_dump(exclude_unset=True)
220
+ existing.update(patch_data)
221
+
222
+ return {"data": existing}
223
+
224
+
225
+ # =====================================================================
226
+ # DELETE /v1/patients/{patient_id} — Remove a patient
227
+ # =====================================================================
228
+ # DELETE removes a resource.
229
+ # We return 204 No Content because the thing is gone — there's nothing
230
+ # to send back.
231
+
232
+
233
+ @app.delete("/v1/patients/{patient_id}", status_code=204, tags=["Patients"])
234
+ def delete_patient(patient_id: str):
235
+ """
236
+ Delete a patient record.
237
+
238
+ REST notes:
239
+ - Returns 204 No Content on success (the resource is gone).
240
+ - Returns 404 if the patient didn't exist to begin with.
241
+ """
242
+ if patient_id not in patients_db:
243
+ raise HTTPException(status_code=404, detail="Patient not found")
244
+
245
+ del patients_db[patient_id]
246
+ # 204 means "success, nothing to return" — FastAPI handles this
247
+ # automatically when status_code=204 and we return None.
248
+
249
+
250
+ # =====================================================================
251
+ # 🎯 YOUR TURN — Challenges
252
+ # =====================================================================
253
+ #
254
+ # Challenge 1 (Easy):
255
+ # Add a GET /v1/patients/count endpoint that returns the total number
256
+ # of patients as {"count": <number>}. What status code should it use?
257
+ #
258
+ # Challenge 2 (Medium):
259
+ # Add a query parameter `min_age` to the list_patients endpoint so
260
+ # clients can do GET /v1/patients?min_age=65 to find elderly patients.
261
+ #
262
+ # Challenge 3 (Stretch):
263
+ # Add a POST /v1/patients/search endpoint that accepts a JSON body
264
+ # with a "query" field and returns patients whose name or condition
265
+ # matches (case-insensitive). Why might you use POST for a search
266
+ # instead of GET? (Hint: GET requests can't have a request body.)
267
+ # See solutions/lab_01_challenge3.md for the answer.
lab_02_train_model/README.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 02 — Train the Model
2
+
3
+ > **Goal:** Train a clinical urgency classifier that you will expose as
4
+ > a REST API in the next lab.
5
+
6
+ > **Time:** ~20 minutes
7
+
8
+ > **Prerequisites:** [Lab 01 — Your First API](../lab_01_your_first_api/README.md)
9
+
10
+ ---
11
+
12
+ ## What You'll Learn
13
+
14
+ - How to build a scikit-learn Pipeline (TF-IDF + Logistic Regression)
15
+ - Why Pipelines are better than separate fit/transform steps
16
+ - How to save a trained model with joblib
17
+ - How to sanity-check predictions before deploying
18
+
19
+ ---
20
+
21
+ ## The Data
22
+
23
+ [data/clinical_notes.csv](../data/clinical_notes.csv) contains 30
24
+ labelled clinical notes:
25
+
26
+ | label | count | examples |
27
+ |---|---|---|
28
+ | `urgent` | 10 | chest pain, GI hemorrhage, status epilepticus |
29
+ | `routine` | 20 | annual physical, follow-up, medication refill |
30
+
31
+ Each row has a `note` (free-text clinical note) and a `label`
32
+ (`urgent` or `routine`).
33
+
34
+ > **Note:** This is a tiny dataset for teaching purposes. In a real
35
+ > project you'd have thousands of notes and would want to address class
36
+ > imbalance more carefully.
37
+
38
+ ---
39
+
40
+ ## Run It
41
+
42
+ ```bash
43
+ # From the project root
44
+ python lab_02_train_model/train.py
45
+ ```
46
+
47
+ You should see output like:
48
+
49
+ ```
50
+ 📂 Loading data from .../data/clinical_notes.csv
51
+ Loaded 30 notes ({'routine': 20, 'urgent': 10})
52
+ Train: 24 notes | Test: 6 notes
53
+ 🏋️ Training pipeline...
54
+ 📊 Test Accuracy: 100.00%
55
+ 💾 Model saved to .../models/urgency_classifier.joblib
56
+ 📋 Metadata saved to .../models/model_meta.json
57
+ 🔍 Sanity-check predictions:
58
+ [ urgent] Patient has acute chest pain and ST-elevation. Troponin rising...
59
+ [routine] Routine annual check-up. All vitals within normal limits...
60
+ ✅ Training complete!
61
+ ```
62
+
63
+ ---
64
+
65
+ ## What Just Happened?
66
+
67
+ 1. **Loaded** `clinical_notes.csv` into a DataFrame
68
+ 2. **Split** into 80% train / 20% test (stratified by label)
69
+ 3. **Built a Pipeline** with:
70
+ - `TfidfVectorizer` — converts text to numerical TF-IDF features
71
+ - `LogisticRegression` — classifies based on those features
72
+ 4. **Trained** the pipeline on the training set
73
+ 5. **Evaluated** on the held-out test set
74
+ 6. **Saved** the pipeline to `models/urgency_classifier.joblib`
75
+ 7. **Saved metadata** to `models/model_meta.json`
76
+ 8. **Ran sanity checks** on a few hand-crafted notes
77
+
78
+ ### Why a Pipeline?
79
+
80
+ Read the detailed explanation in [train.py](train.py). The short
81
+ version: a Pipeline bundles TF-IDF and the classifier into one object
82
+ so you can't accidentally forget a preprocessing step when making
83
+ predictions later.
84
+
85
+ ---
86
+
87
+ ## Connection to the ci-cd-template
88
+
89
+ If you completed the [ci-cd-template tutorial](https://github.com/po-DRA/ci-cd-template),
90
+ you already trained a model using a similar pattern. The key
91
+ difference here is that we are training the model so we can **serve it
92
+ as an API** — not just use it in a notebook.
93
+
94
+ The training script is inspired by:
95
+ [ci-cd-template/scripts/train.py](https://github.com/po-DRA/ci-cd-template/blob/main/scripts/train.py)
96
+
97
+ ---
98
+
99
+ ## 🎯 Challenges
100
+
101
+ 1. **(Easy)** Open `models/model_meta.json` and inspect it. What
102
+ accuracy did you get?
103
+ 2. **(Medium)** Add 5 more clinical notes to `clinical_notes.csv`
104
+ and retrain. Does the accuracy change?
105
+ 3. **(Stretch)** Modify `train.py` to also save a confusion matrix
106
+ as `models/confusion_matrix.json`.
107
+
108
+ ---
109
+
110
+ ## ✅ Done When
111
+
112
+ - [ ] `models/urgency_classifier.joblib` exists
113
+ - [ ] `models/model_meta.json` exists and looks correct
114
+ - [ ] The sanity-check predictions make medical sense
115
+ - [ ] You understand why we use a Pipeline
116
+
117
+ ---
118
+
119
+ **Next →** [Lab 03: Expose the Model as an API](../lab_03_expose_model/README.md)
lab_02_train_model/train.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lab 02 — Train a Clinical Urgency Classifier
3
+ =============================================
4
+ This script trains a machine learning model that classifies clinical
5
+ notes as "urgent" or "routine".
6
+
7
+ It uses:
8
+ - TF-IDF to convert text into numbers (bag-of-words on steroids)
9
+ - Logistic Regression to classify the notes
10
+ - A scikit-learn Pipeline to bundle both steps together
11
+
12
+ How to run:
13
+ python lab_02_train_model/train.py
14
+
15
+ After running you will find:
16
+ models/urgency_classifier.joblib ← the trained pipeline
17
+ models/model_meta.json ← accuracy, date, class labels
18
+
19
+ Why a Pipeline?
20
+ A Pipeline chains preprocessing (TF-IDF) and the classifier into a
21
+ single object. This means:
22
+ 1. You can't accidentally forget to transform new data
23
+ 2. You save/load ONE object instead of two
24
+ 3. Cross-validation and grid search work out of the box
25
+ It's the recommended scikit-learn pattern for any text classifier.
26
+
27
+ Reference:
28
+ Training script inspiration:
29
+ https://github.com/po-DRA/ci-cd-template/blob/main/scripts/train.py
30
+ Deploying ML models with FastAPI:
31
+ https://www.analyticsvidhya.com/blog/2022/09/deploying-ml-models-using-fastapi/
32
+ """
33
+
34
+ import json
35
+ import os
36
+ from datetime import UTC, datetime
37
+
38
+ import joblib
39
+ import pandas as pd
40
+ from sklearn.feature_extraction.text import TfidfVectorizer
41
+ from sklearn.linear_model import LogisticRegression
42
+ from sklearn.metrics import accuracy_score, classification_report
43
+ from sklearn.model_selection import train_test_split
44
+ from sklearn.pipeline import Pipeline
45
+
46
+ # ── Paths ───────────────────────────────────────────────────────────
47
+ # We use os.path so this script works from any working directory.
48
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
49
+ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
50
+ DATA_PATH = os.path.join(PROJECT_ROOT, "data", "clinical_notes.csv")
51
+ MODEL_DIR = os.path.join(PROJECT_ROOT, "models")
52
+ MODEL_PATH = os.path.join(MODEL_DIR, "urgency_classifier.joblib")
53
+ META_PATH = os.path.join(MODEL_DIR, "model_meta.json")
54
+
55
+
56
+ def train():
57
+ """Train the urgency classifier and save it to disk."""
58
+
59
+ # ── 1. Load the data ────────────────────────────────────────────
60
+ print("[LOAD] Loading data from", DATA_PATH)
61
+ df = pd.read_csv(DATA_PATH)
62
+ print(f" Loaded {len(df)} notes ({df['label'].value_counts().to_dict()})")
63
+
64
+ X = df["note"] # The clinical note text
65
+ y = df["label"] # "urgent" or "routine"
66
+
67
+ # ── 2. Split into train / test ──────────────────────────────────
68
+ # We hold out 20% of the data to check how well the model
69
+ # generalises to notes it has never seen.
70
+ # stratify=y ensures both sets have the same ratio of urgent/routine.
71
+ X_train, X_test, y_train, y_test = train_test_split(
72
+ X,
73
+ y,
74
+ test_size=0.2,
75
+ random_state=42, # reproducible split
76
+ stratify=y, # keep class balance
77
+ )
78
+ print(f" Train: {len(X_train)} notes | Test: {len(X_test)} notes")
79
+
80
+ # ── 3. Build the Pipeline ───────────────────────────────────────
81
+ # Why a Pipeline?
82
+ # - TfidfVectorizer converts text → sparse matrix of TF-IDF features.
83
+ # TF-IDF stands for Term Frequency–Inverse Document Frequency.
84
+ # It rewards words that are frequent in one document but rare
85
+ # across all documents (i.e., distinctive words).
86
+ # - LogisticRegression learns which TF-IDF features predict
87
+ # "urgent" vs "routine".
88
+ # - Wrapping them in a Pipeline means we call .fit() and .predict()
89
+ # once, and scikit-learn handles the transformations internally.
90
+ pipeline = Pipeline(
91
+ [
92
+ (
93
+ "tfidf",
94
+ TfidfVectorizer(
95
+ max_features=5000, # keep the top 5000 words
96
+ ngram_range=(1, 2), # use single words AND two-word phrases
97
+ stop_words="english", # drop common words like "the", "is"
98
+ ),
99
+ ),
100
+ (
101
+ "clf",
102
+ LogisticRegression(
103
+ max_iter=1000, # enough iterations to converge
104
+ class_weight="balanced", # handle class imbalance (fewer urgent than routine)
105
+ random_state=42,
106
+ ),
107
+ ),
108
+ ]
109
+ )
110
+
111
+ # ── 4. Train the model ──────────────────────────────────────────
112
+ print("[TRAIN] Training pipeline...")
113
+ pipeline.fit(X_train, y_train)
114
+
115
+ # ── 5. Evaluate on the test set ───────────────────��─────────────
116
+ y_pred = pipeline.predict(X_test)
117
+ accuracy = accuracy_score(y_test, y_pred)
118
+ report = classification_report(y_test, y_pred, zero_division=0)
119
+
120
+ print(f"\n[EVAL] Test Accuracy: {accuracy:.2%}")
121
+ print(report)
122
+
123
+ # ── 6. Save the model ──────────────────────────────────────────
124
+ os.makedirs(MODEL_DIR, exist_ok=True)
125
+
126
+ # joblib is the recommended way to serialise scikit-learn models.
127
+ # It handles numpy arrays and sparse matrices efficiently.
128
+ joblib.dump(pipeline, MODEL_PATH)
129
+ print(f"[SAVE] Model saved to {MODEL_PATH}")
130
+
131
+ # Save metadata so the API can report model info without loading
132
+ # the full pipeline into memory just to answer "what version is this?"
133
+ meta = {
134
+ "model_type": "TF-IDF + Logistic Regression Pipeline",
135
+ "accuracy": round(accuracy, 4),
136
+ "train_size": len(X_train),
137
+ "test_size": len(X_test),
138
+ "classes": list(pipeline.classes_),
139
+ "n_features": pipeline.named_steps["tfidf"].max_features,
140
+ "trained_at": datetime.now(UTC).isoformat(),
141
+ }
142
+ with open(META_PATH, "w") as f:
143
+ json.dump(meta, f, indent=2)
144
+ print(f"[META] Metadata saved to {META_PATH}")
145
+
146
+ # ── 7. Sanity check — try some predictions ─────────────────────
147
+ # These quick checks let you confirm the model "makes sense"
148
+ # before you wire it up as an API.
149
+ print("\n[CHECK] Sanity-check predictions:")
150
+ test_notes = [
151
+ "Patient has acute chest pain and ST-elevation. Troponin rising.",
152
+ "Routine annual check-up. All vitals within normal limits.",
153
+ "Massive GI bleed, hemoglobin dropping rapidly. Transfusion needed.",
154
+ "Follow-up for well-controlled hypertension. Continue current meds.",
155
+ ]
156
+ predictions = pipeline.predict(test_notes)
157
+ for note, pred in zip(test_notes, predictions, strict=True):
158
+ print(f" [{pred:>7s}] {note[:70]}...")
159
+
160
+ print("\n[DONE] Training complete!")
161
+
162
+
163
+ if __name__ == "__main__":
164
+ train()
lab_03_expose_model/README.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 03 — Expose the Model as a REST API
2
+
3
+ > **Goal:** Serve the trained urgency classifier as a REST API so
4
+ > anyone can send a clinical note and get a prediction back.
5
+
6
+ > **Time:** ~30 minutes
7
+
8
+ > **Prerequisites:**
9
+ > [Lab 02 — Train the Model](../lab_02_train_model/README.md) (model
10
+ > must be trained first)
11
+
12
+ ---
13
+
14
+ ## What You'll Learn
15
+
16
+ - How to load an ML model at API startup (lifespan context)
17
+ - How to design prediction endpoints following REST principles
18
+ - How to return confidence scores alongside predictions
19
+ - How to store and retrieve prediction history
20
+
21
+ ---
22
+
23
+ ## Setup
24
+
25
+ ```bash
26
+ # 1. Make sure the model is trained
27
+ python lab_02_train_model/train.py
28
+
29
+ # 2. Start the prediction API
30
+ cd lab_03_expose_model
31
+ uvicorn app:app --reload
32
+ ```
33
+
34
+ Open http://127.0.0.1:8000/docs to explore.
35
+
36
+ ---
37
+
38
+ ## Endpoints Overview
39
+
40
+ | Method | Endpoint | What It Does | Status Code |
41
+ |---|---|---|---|
42
+ | POST | `/v1/predictions` | Classify a clinical note | 201 |
43
+ | GET | `/v1/predictions` | List stored predictions | 200 |
44
+ | GET | `/v1/predictions/{id}` | Get one prediction | 200 / 404 |
45
+ | DELETE | `/v1/predictions/{id}` | Delete a prediction | 204 / 404 |
46
+ | GET | `/v1/model/info` | Model metadata | 200 / 503 |
47
+
48
+ ---
49
+
50
+ ## Try It
51
+
52
+ ### Submit a prediction
53
+ ```bash
54
+ curl -X POST http://127.0.0.1:8000/v1/predictions \
55
+ -H "Content-Type: application/json" \
56
+ -d '{"note": "Patient has acute chest pain radiating to left arm with diaphoresis"}'
57
+ ```
58
+
59
+ Expected response (201 Created):
60
+ ```json
61
+ {
62
+ "data": {
63
+ "id": "abc-123...",
64
+ "note": "Patient has acute chest pain...",
65
+ "prediction": "urgent",
66
+ "confidence": 0.9812,
67
+ "created_at": "2025-..."
68
+ },
69
+ "meta": {"model_version": "2025-..."}
70
+ }
71
+ ```
72
+
73
+ ### List all predictions
74
+ ```bash
75
+ curl http://127.0.0.1:8000/v1/predictions
76
+ ```
77
+
78
+ ### Filter by label
79
+ ```bash
80
+ curl "http://127.0.0.1:8000/v1/predictions?prediction=urgent"
81
+ ```
82
+
83
+ ### Check model info
84
+ ```bash
85
+ curl http://127.0.0.1:8000/v1/model/info
86
+ ```
87
+
88
+ ---
89
+
90
+ ## Key Architecture Decisions
91
+
92
+ Read through [app.py](app.py) — every decision is commented. The
93
+ highlights:
94
+
95
+ 1. **Model loaded once at startup** — not on every request. Loading a
96
+ model from disk can take hundreds of milliseconds. Doing it once
97
+ saves all that time for every subsequent request.
98
+
99
+ 2. **Predictions stored with UUIDs** — clients can retrieve, list, and
100
+ delete them later. This is REST: predictions are a *resource*.
101
+
102
+ 3. **Consistent response envelope** — every response is
103
+ `{data: ..., meta: ...}`. Clients always know where to find the
104
+ payload.
105
+
106
+ 4. **503 when model missing** — the API starts even without a model,
107
+ but prediction endpoints return `503 Service Unavailable` with a
108
+ helpful message.
109
+
110
+ ---
111
+
112
+ ## 🎯 Challenges
113
+
114
+ See the YOUR TURN section at the bottom of [app.py](app.py):
115
+
116
+ 1. **(Easy)** Add a stats endpoint
117
+ 2. **(Medium)** Add confidence filtering
118
+ 3. **(Stretch)** Add batch predictions
119
+
120
+ ---
121
+
122
+ ## ✅ Done When
123
+
124
+ - [ ] You can POST a clinical note and get a prediction back (201)
125
+ - [ ] You can GET the list of predictions with filtering
126
+ - [ ] You can DELETE a prediction (204)
127
+ - [ ] The `/v1/model/info` endpoint returns model metadata
128
+ - [ ] You understand why the model is loaded at startup, not per-request
129
+
130
+ ---
131
+
132
+ **Next →** [Lab 04: Test the API](../lab_04_test_api/README.md)
lab_03_expose_model/__init__.py ADDED
File without changes
lab_03_expose_model/app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lab 03 — Expose the Trained Model as a REST API
3
+ ================================================
4
+ This FastAPI app loads the trained urgency classifier and serves it
5
+ as a RESTful prediction service.
6
+
7
+ How to run:
8
+ # First, make sure you trained the model (Lab 02):
9
+ python lab_02_train_model/train.py
10
+
11
+ # Then start this API:
12
+ cd lab_03_expose_model
13
+ uvicorn app:app --reload
14
+
15
+ # Open http://127.0.0.1:8000/docs to try it out!
16
+
17
+ Architecture decisions:
18
+ - Model is loaded ONCE at startup using FastAPI's lifespan context.
19
+ This avoids reloading a 10 MB model on every single request.
20
+ - Predictions are stored in memory with UUIDs so clients can
21
+ retrieve, list, and delete them (full CRUD on predictions).
22
+ - Every response uses a consistent envelope: {data: ..., meta: ...}
23
+ - Endpoints follow REST conventions from Lab 00.
24
+
25
+ Reference:
26
+ - Deploying ML models with FastAPI:
27
+ https://www.analyticsvidhya.com/blog/2022/09/deploying-ml-models-using-fastapi/
28
+ - FastAPI lifespan:
29
+ https://fastapi.tiangolo.com/advanced/events/
30
+ """
31
+
32
+ import json
33
+ import os
34
+ from contextlib import asynccontextmanager
35
+ from datetime import UTC, datetime
36
+ from uuid import uuid4
37
+
38
+ import joblib
39
+ from fastapi import FastAPI, HTTPException, Query
40
+ from pydantic import BaseModel, Field
41
+
42
+ # ── Paths ───────────────────────────────────────────────────────────
43
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
44
+ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
45
+ MODEL_PATH = os.path.join(PROJECT_ROOT, "models", "urgency_classifier.joblib")
46
+ META_PATH = os.path.join(PROJECT_ROOT, "models", "model_meta.json")
47
+
48
+ # ── Global state ────────────────────────────────────────────────────
49
+ # These are set during startup (see lifespan below).
50
+ model = None
51
+ model_meta = None
52
+
53
+ # In-memory store for predictions (dict of UUID → prediction record)
54
+ predictions_db: dict[str, dict] = {}
55
+
56
+
57
+ # ── Lifespan: load model once at startup ────────────────────────────
58
+ # FastAPI's lifespan context manager runs code BEFORE the first request
59
+ # and AFTER the last request. Perfect for loading/unloading heavy
60
+ # resources like ML models.
61
+ #
62
+ # Why not load in a global variable?
63
+ # - The lifespan pattern is the official FastAPI recommendation.
64
+ # - It makes startup failures explicit and logged.
65
+ # - It gives you a clean place to release resources on shutdown.
66
+
67
+
68
+ @asynccontextmanager
69
+ async def lifespan(app: FastAPI):
70
+ """Load the model at startup, release at shutdown."""
71
+ global model, model_meta
72
+
73
+ # --- Startup ---
74
+ if os.path.exists(MODEL_PATH):
75
+ model = joblib.load(MODEL_PATH)
76
+ print(f"[OK] Model loaded from {MODEL_PATH}")
77
+ else:
78
+ print(f"[WARN] Model not found at {MODEL_PATH}")
79
+ print(" Run 'python lab_02_train_model/train.py' first.")
80
+ print(" The API will start but prediction endpoints won't work.")
81
+
82
+ if os.path.exists(META_PATH):
83
+ with open(META_PATH) as f:
84
+ model_meta = json.load(f)
85
+
86
+ yield # ← the app runs here
87
+
88
+ # --- Shutdown ---
89
+ print("[SHUTDOWN] Releasing model from memory")
90
+ model = None
91
+ model_meta = None
92
+
93
+
94
+ # ── Create the FastAPI app ──────────────────────────────────────────
95
+ app = FastAPI(
96
+ title="Clinical Urgency Prediction API",
97
+ description="Predicts whether a clinical note is urgent or routine",
98
+ version="1.0.0",
99
+ lifespan=lifespan,
100
+ )
101
+
102
+
103
+ # ── Pydantic models ────────────────────────────────────────────────
104
+
105
+
106
+ class PredictionRequest(BaseModel):
107
+ """What the client sends to request a prediction."""
108
+
109
+ note: str = Field(
110
+ ...,
111
+ min_length=10,
112
+ description="The clinical note to classify",
113
+ json_schema_extra={
114
+ "example": "Patient presents with acute chest pain and shortness of breath."
115
+ },
116
+ )
117
+
118
+
119
+ class PredictionResponse(BaseModel):
120
+ """What the server returns for a single prediction."""
121
+
122
+ id: str
123
+ note: str
124
+ prediction: str
125
+ confidence: float
126
+ created_at: str
127
+
128
+
129
+ # ── Helper ──────────────────────────────────────────────────────────
130
+
131
+
132
+ def _require_model():
133
+ """Raise 503 if the model is not loaded."""
134
+ if model is None:
135
+ raise HTTPException(
136
+ status_code=503,
137
+ detail="Model not loaded. Run 'python lab_02_train_model/train.py' first.",
138
+ )
139
+
140
+
141
+ # =====================================================================
142
+ # POST /v1/predictions — Create a new prediction
143
+ # =====================================================================
144
+ # POST because we are CREATING a new resource (the prediction record).
145
+ # Returns 201 Created with the prediction in the body.
146
+
147
+
148
+ @app.post("/v1/predictions", status_code=201, tags=["Predictions"])
149
+ def create_prediction(request: PredictionRequest):
150
+ """
151
+ Classify a clinical note as urgent or routine.
152
+
153
+ REST notes:
154
+ - POST creates a new prediction resource (assigned a UUID).
155
+ - Returns 201 Created because a new resource was stored.
156
+ - Returns 503 if the model is not available.
157
+ """
158
+ _require_model()
159
+
160
+ # Get the prediction and confidence
161
+ prediction = model.predict([request.note])[0]
162
+ probabilities = model.predict_proba([request.note])[0]
163
+ confidence = float(max(probabilities))
164
+
165
+ # Store the prediction with a UUID
166
+ pred_id = str(uuid4())
167
+ record = {
168
+ "id": pred_id,
169
+ "note": request.note,
170
+ "prediction": prediction,
171
+ "confidence": round(confidence, 4),
172
+ "created_at": datetime.now(UTC).isoformat(),
173
+ }
174
+ predictions_db[pred_id] = record
175
+
176
+ return {
177
+ "data": record,
178
+ "meta": {
179
+ "model_version": model_meta.get("trained_at", "unknown") if model_meta else "unknown"
180
+ },
181
+ }
182
+
183
+
184
+ # =====================================================================
185
+ # GET /v1/predictions — List all predictions (with filtering & pagination)
186
+ # =====================================================================
187
+
188
+
189
+ @app.get("/v1/predictions", status_code=200, tags=["Predictions"])
190
+ def list_predictions(
191
+ prediction: str | None = Query(
192
+ None,
193
+ description="Filter by prediction label (urgent or routine)",
194
+ ),
195
+ limit: int = Query(10, ge=1, le=100, description="Max results"),
196
+ offset: int = Query(0, ge=0, description="Results to skip"),
197
+ ):
198
+ """
199
+ List stored predictions with optional filtering and pagination.
200
+
201
+ REST notes:
202
+ - GET for reading, query params for filtering/pagination.
203
+ - This endpoint works even if the model is not loaded (you can
204
+ still browse old predictions).
205
+ """
206
+ results = list(predictions_db.values())
207
+
208
+ # Filter by prediction label if requested
209
+ if prediction:
210
+ results = [r for r in results if r["prediction"] == prediction]
211
+
212
+ total = len(results)
213
+ results = results[offset : offset + limit]
214
+
215
+ return {
216
+ "data": results,
217
+ "meta": {"total": total, "limit": limit, "offset": offset},
218
+ }
219
+
220
+
221
+ # =====================================================================
222
+ # GET /v1/predictions/{prediction_id} — Get one prediction
223
+ # =====================================================================
224
+
225
+
226
+ @app.get("/v1/predictions/{prediction_id}", status_code=200, tags=["Predictions"])
227
+ def get_prediction(prediction_id: str):
228
+ """
229
+ Retrieve a specific prediction by its ID.
230
+
231
+ REST notes:
232
+ - Path parameter identifies the specific resource.
233
+ - Returns 404 if not found.
234
+ """
235
+ if prediction_id not in predictions_db:
236
+ raise HTTPException(status_code=404, detail="Prediction not found")
237
+ return {"data": predictions_db[prediction_id]}
238
+
239
+
240
+ # =====================================================================
241
+ # DELETE /v1/predictions/{prediction_id} — Delete a prediction
242
+ # =====================================================================
243
+
244
+
245
+ @app.delete("/v1/predictions/{prediction_id}", status_code=204, tags=["Predictions"])
246
+ def delete_prediction(prediction_id: str):
247
+ """
248
+ Delete a stored prediction.
249
+
250
+ REST notes:
251
+ - Returns 204 No Content on success.
252
+ - Returns 404 if the prediction doesn't exist.
253
+ """
254
+ if prediction_id not in predictions_db:
255
+ raise HTTPException(status_code=404, detail="Prediction not found")
256
+ del predictions_db[prediction_id]
257
+
258
+
259
+ # =====================================================================
260
+ # GET /v1/model/info — Model metadata
261
+ # =====================================================================
262
+
263
+
264
+ @app.get("/v1/model/info", status_code=200, tags=["Model"])
265
+ def get_model_info():
266
+ """
267
+ Return metadata about the loaded model.
268
+
269
+ REST notes:
270
+ - This is a read-only informational endpoint.
271
+ - Returns 503 if no model metadata is available.
272
+ """
273
+ if model_meta is None:
274
+ raise HTTPException(
275
+ status_code=503,
276
+ detail="Model metadata not available.",
277
+ )
278
+ return {
279
+ "data": model_meta,
280
+ "meta": {"model_loaded": model is not None},
281
+ }
282
+
283
+
284
+ # =====================================================================
285
+ # 🎯 YOUR TURN — Challenges
286
+ # =====================================================================
287
+ #
288
+ # Challenge 1 (Easy):
289
+ # Add a GET /v1/predictions/stats endpoint that returns:
290
+ # {"total": N, "urgent": N, "routine": N}
291
+ # showing counts of each prediction type stored.
292
+ #
293
+ # Challenge 2 (Medium):
294
+ # Add a min_confidence query parameter to the list endpoint
295
+ # so clients can filter for high-confidence predictions only:
296
+ # GET /v1/predictions?min_confidence=0.9
297
+ #
298
+ # Challenge 3 (Stretch):
299
+ # Add a POST /v1/predictions/batch endpoint that accepts a list
300
+ # of notes and returns predictions for all of them in one call.
301
+ # This is a common pattern for ML APIs — it reduces network
302
+ # round-trips when you have many items to classify.
lab_04_test_api/README.md ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 04 — Test the API
2
+
3
+ > **Goal:** Write automated tests for the prediction API using pytest
4
+ > and FastAPI's TestClient.
5
+
6
+ > **Time:** ~25 minutes
7
+
8
+ > **Prerequisites:**
9
+ > [Lab 03 — Expose the Model](../lab_03_expose_model/README.md)
10
+
11
+ ---
12
+
13
+ ## What You'll Learn
14
+
15
+ - How to use FastAPI's TestClient (no server needed!)
16
+ - How to test every HTTP verb and status code
17
+ - How to validate response shapes
18
+ - How to skip tests gracefully when the model isn't available
19
+
20
+ ---
21
+
22
+ ## Why Test an API?
23
+
24
+ 1. **Catch bugs before deployment** — a broken endpoint in production
25
+ could affect clinical workflows.
26
+ 2. **Verify REST conventions** — did you return 201 for POST? 204 for
27
+ DELETE? Tests enforce this.
28
+ 3. **Tests ARE documentation** — a new team member can read the tests
29
+ to understand exactly what each endpoint does.
30
+ 4. **Refactor with confidence** — change the code, run the tests, know
31
+ nothing is broken.
32
+
33
+ ---
34
+
35
+ ## Run the Tests
36
+
37
+ ```bash
38
+ # From the project root
39
+ pytest lab_04_test_api/test_api.py -v
40
+ ```
41
+
42
+ The `-v` flag shows each test name and its result.
43
+
44
+ Expected output (if model is trained):
45
+ ```
46
+ test_create_prediction_returns_201 PASSED
47
+ test_create_prediction_returns_data_envelope PASSED
48
+ test_empty_note_returns_422 PASSED
49
+ test_get_nonexistent_returns_404 PASSED
50
+ test_delete_existing_returns_204 PASSED
51
+ ...
52
+ ```
53
+
54
+ If the model is not trained, model-dependent tests are **skipped**
55
+ (not failed):
56
+ ```
57
+ test_create_prediction_returns_201 SKIPPED (Model not trained)
58
+ ```
59
+
60
+ ---
61
+
62
+ ## What the Tests Cover
63
+
64
+ | Category | What's Tested | Expected Code |
65
+ |---|---|---|
66
+ | **POST** | Create prediction | 201 |
67
+ | **POST** | Missing note field | 422 |
68
+ | **POST** | Note too short | 422 |
69
+ | **GET** | List predictions | 200 |
70
+ | **GET** | Empty list | 200 (not 404!) |
71
+ | **GET** | Filter by label | 200 |
72
+ | **GET** | Pagination | 200 |
73
+ | **GET** | Specific prediction | 200 |
74
+ | **GET** | Nonexistent prediction | 404 |
75
+ | **DELETE** | Remove prediction | 204 |
76
+ | **DELETE** | Nonexistent prediction | 404 |
77
+ | **Model info** | Metadata endpoint | 200 |
78
+
79
+ ---
80
+
81
+ ## Code Walkthrough
82
+
83
+ Open [test_api.py](test_api.py) and notice:
84
+
85
+ 1. **TestClient** — lets you test without starting a real server.
86
+ It simulates HTTP requests in-process.
87
+
88
+ 2. **`clear_predictions` fixture** — resets the database before each
89
+ test so tests don't depend on each other.
90
+
91
+ 3. **`skip_without_model`** — tests that need the model are skipped
92
+ (not failed) if the model isn't trained yet.
93
+
94
+ 4. **Class-based grouping** — tests are organized by HTTP verb for
95
+ readability.
96
+
97
+ ---
98
+
99
+ ## 🎯 Challenges
100
+
101
+ See the YOUR TURN section at the bottom of [test_api.py](test_api.py):
102
+
103
+ 1. **(Easy)** Test that total count is correct after creating 5 predictions
104
+ 2. **(Medium)** Test double-delete behavior
105
+ 3. **(Stretch)** Parameterized test for multiple clinical notes
106
+
107
+ ---
108
+
109
+ ## ✅ Done When
110
+
111
+ - [ ] All tests pass (or skip gracefully if model not trained)
112
+ - [ ] You understand what each test is checking
113
+ - [ ] You can explain why an empty list returns 200, not 404
114
+ - [ ] You attempted at least one challenge
115
+
116
+ ---
117
+
118
+ **Next →** [Lab 05: Deploy](../lab_05_deploy/README.md)
lab_04_test_api/test_api.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lab 04 — Test the REST API with pytest
3
+ =======================================
4
+ Automated tests for the prediction API using FastAPI's TestClient.
5
+
6
+ How to run:
7
+ pytest lab_04_test_api/test_api.py -v
8
+
9
+ What this tests:
10
+ - All HTTP verbs (GET, POST, DELETE)
11
+ - Correct status codes (200, 201, 204, 404, 422)
12
+ - Response shape validation ({data: ..., meta: ...})
13
+ - Filtering and pagination
14
+ - Graceful handling when model is not loaded
15
+
16
+ Why test an API?
17
+ - Catch bugs before deployment
18
+ - Verify REST conventions (correct status codes!)
19
+ - Document expected behavior (tests ARE documentation)
20
+ - Enable confident refactoring later
21
+
22
+ Reference:
23
+ - FastAPI testing docs: https://fastapi.tiangolo.com/tutorial/testing/
24
+ - pytest docs: https://docs.pytest.org/
25
+ """
26
+
27
+ import os
28
+
29
+ import pytest
30
+ from fastapi.testclient import TestClient
31
+
32
+ # ── Import the app ──────────────────────────────────────────────────
33
+ # We import from lab_03 because that's the full prediction API.
34
+ from lab_03_expose_model.app import MODEL_PATH, app, predictions_db
35
+
36
+ # ── Helper ──────────────────────────────────────────────────────────
37
+ # Some tests need the ML model loaded. If it's not available (e.g.
38
+ # the learner hasn't trained it yet), we skip those tests gracefully
39
+ # instead of failing with a confusing error.
40
+ #
41
+ # We check if the model FILE exists (not the in-memory variable)
42
+ # because the model is loaded at app startup via the lifespan context,
43
+ # which only runs when the TestClient is used.
44
+
45
+ MODEL_LOADED = os.path.exists(MODEL_PATH)
46
+ skip_without_model = pytest.mark.skipif(
47
+ not MODEL_LOADED,
48
+ reason="Model not trained yet — run 'python lab_02_train_model/train.py'",
49
+ )
50
+
51
+
52
+ # ── Fixtures ────────────────────────────────────────────────────────
53
+
54
+
55
+ @pytest.fixture(scope="module")
56
+ def client():
57
+ """Create a TestClient with lifespan support.
58
+
59
+ Using TestClient as a context manager ensures the lifespan runs,
60
+ which loads the ML model at startup and cleans up on shutdown.
61
+ The 'module' scope means this runs once for all tests in this file.
62
+ """
63
+ with TestClient(app) as c:
64
+ yield c
65
+
66
+
67
+ @pytest.fixture(autouse=True)
68
+ def clear_predictions():
69
+ """Clear the predictions database before each test.
70
+
71
+ This ensures tests are independent — one test's predictions
72
+ don't leak into another test.
73
+ """
74
+ predictions_db.clear()
75
+ yield
76
+ predictions_db.clear()
77
+
78
+
79
+ # =====================================================================
80
+ # Tests for POST /v1/predictions
81
+ # =====================================================================
82
+
83
+
84
+ @skip_without_model
85
+ class TestCreatePrediction:
86
+ """Tests for creating predictions (POST)."""
87
+
88
+ def test_create_prediction_returns_201(self, client):
89
+ """POST should return 201 Created — the correct REST status
90
+ code for creating a new resource."""
91
+ response = client.post(
92
+ "/v1/predictions",
93
+ json={"note": "Patient has acute chest pain with ST elevation on ECG"},
94
+ )
95
+ assert response.status_code == 201
96
+
97
+ def test_create_prediction_returns_data_envelope(self, client):
98
+ """Response must use our standard {data: ..., meta: ...} envelope."""
99
+ response = client.post(
100
+ "/v1/predictions",
101
+ json={"note": "Routine annual physical. All vitals within normal limits."},
102
+ )
103
+ body = response.json()
104
+ assert "data" in body
105
+ assert "meta" in body
106
+
107
+ def test_create_prediction_has_required_fields(self, client):
108
+ """The prediction record must include id, note, prediction,
109
+ confidence, and created_at."""
110
+ response = client.post(
111
+ "/v1/predictions",
112
+ json={"note": "Patient found unresponsive with GCS of 3. Emergency intubation needed."},
113
+ )
114
+ data = response.json()["data"]
115
+ assert "id" in data
116
+ assert "note" in data
117
+ assert "prediction" in data
118
+ assert "confidence" in data
119
+ assert "created_at" in data
120
+
121
+ def test_prediction_is_urgent_or_routine(self, client):
122
+ """Model should return one of the two known labels."""
123
+ response = client.post(
124
+ "/v1/predictions",
125
+ json={"note": "Massive upper GI hemorrhage. Hemoglobin dropping rapidly."},
126
+ )
127
+ prediction = response.json()["data"]["prediction"]
128
+ assert prediction in ("urgent", "routine")
129
+
130
+ def test_confidence_is_between_0_and_1(self, client):
131
+ """Confidence score must be a probability (0 to 1)."""
132
+ response = client.post(
133
+ "/v1/predictions",
134
+ json={"note": "Follow-up for well-controlled diabetes. HbA1c stable."},
135
+ )
136
+ confidence = response.json()["data"]["confidence"]
137
+ assert 0.0 <= confidence <= 1.0
138
+
139
+ def test_empty_note_returns_422(self, client):
140
+ """Sending a note that is too short should return 422
141
+ Unprocessable Entity — FastAPI validates this automatically
142
+ because we set min_length=10 on the Pydantic model."""
143
+ response = client.post(
144
+ "/v1/predictions",
145
+ json={"note": "short"},
146
+ )
147
+ assert response.status_code == 422
148
+
149
+ def test_missing_note_returns_422(self, client):
150
+ """Sending no note at all should return 422."""
151
+ response = client.post("/v1/predictions", json={})
152
+ assert response.status_code == 422
153
+
154
+
155
+ # =====================================================================
156
+ # Tests for GET /v1/predictions
157
+ # =====================================================================
158
+
159
+
160
+ @skip_without_model
161
+ class TestListPredictions:
162
+ """Tests for listing predictions (GET)."""
163
+
164
+ def test_empty_list_returns_200(self, client):
165
+ """An empty collection should return 200 with an empty list —
166
+ not 404. An empty list IS a valid response."""
167
+ response = client.get("/v1/predictions")
168
+ assert response.status_code == 200
169
+ assert response.json()["data"] == []
170
+
171
+ def test_list_returns_created_predictions(self, client):
172
+ """After creating predictions, the list should include them."""
173
+ # Create two predictions
174
+ client.post(
175
+ "/v1/predictions",
176
+ json={"note": "Acute respiratory distress. SpO2 falling rapidly."},
177
+ )
178
+ client.post(
179
+ "/v1/predictions",
180
+ json={"note": "Routine prenatal visit. Fetal heart tones normal."},
181
+ )
182
+ response = client.get("/v1/predictions")
183
+ assert response.status_code == 200
184
+ assert len(response.json()["data"]) == 2
185
+
186
+ def test_filter_by_prediction_label(self, client):
187
+ """Query param ?prediction=urgent should filter results."""
188
+ # Create one of each
189
+ client.post(
190
+ "/v1/predictions",
191
+ json={"note": "Acute chest pain with troponin elevation and diaphoresis."},
192
+ )
193
+ client.post(
194
+ "/v1/predictions",
195
+ json={"note": "Routine well-child visit. Growth on track. Immunizations current."},
196
+ )
197
+ response = client.get("/v1/predictions?prediction=urgent")
198
+ assert response.status_code == 200
199
+ for item in response.json()["data"]:
200
+ assert item["prediction"] == "urgent"
201
+
202
+ def test_pagination_with_limit_and_offset(self, client):
203
+ """limit and offset should control pagination."""
204
+ # Create 3 predictions
205
+ for note in [
206
+ "Emergency: massive hemorrhage requiring immediate intervention.",
207
+ "Routine follow-up for managed hypothyroidism. TSH normal.",
208
+ "Status epilepticus. Benzodiazepines administered without effect.",
209
+ ]:
210
+ client.post("/v1/predictions", json={"note": note})
211
+
212
+ # Get first 2
213
+ response = client.get("/v1/predictions?limit=2&offset=0")
214
+ assert len(response.json()["data"]) == 2
215
+
216
+ # Get the third
217
+ response = client.get("/v1/predictions?limit=2&offset=2")
218
+ assert len(response.json()["data"]) == 1
219
+
220
+ def test_meta_includes_total_count(self, client):
221
+ """The meta section should include the total count for
222
+ pagination UI."""
223
+ client.post(
224
+ "/v1/predictions",
225
+ json={"note": "Patient presenting with acute abdomen and rebound tenderness."},
226
+ )
227
+ response = client.get("/v1/predictions")
228
+ meta = response.json()["meta"]
229
+ assert "total" in meta
230
+ assert meta["total"] == 1
231
+
232
+
233
+ # =====================================================================
234
+ # Tests for GET /v1/predictions/{id}
235
+ # =====================================================================
236
+
237
+
238
+ @skip_without_model
239
+ class TestGetPrediction:
240
+ """Tests for getting a specific prediction (GET by ID)."""
241
+
242
+ def test_get_existing_returns_200(self, client):
243
+ """Getting a prediction that exists should return 200."""
244
+ create = client.post(
245
+ "/v1/predictions",
246
+ json={"note": "Suspected pulmonary embolism with acute dyspnea and pleuritic pain."},
247
+ )
248
+ pred_id = create.json()["data"]["id"]
249
+
250
+ response = client.get(f"/v1/predictions/{pred_id}")
251
+ assert response.status_code == 200
252
+ assert response.json()["data"]["id"] == pred_id
253
+
254
+ def test_get_nonexistent_returns_404(self, client):
255
+ """Getting a prediction that doesn't exist should return 404 —
256
+ the correct REST response for 'resource not found'."""
257
+ response = client.get("/v1/predictions/nonexistent-id")
258
+ assert response.status_code == 404
259
+
260
+
261
+ # =====================================================================
262
+ # Tests for DELETE /v1/predictions/{id}
263
+ # =====================================================================
264
+
265
+
266
+ @skip_without_model
267
+ class TestDeletePrediction:
268
+ """Tests for deleting predictions (DELETE)."""
269
+
270
+ def test_delete_existing_returns_204(self, client):
271
+ """DELETE should return 204 No Content — the resource is gone,
272
+ there's nothing to send back."""
273
+ create = client.post(
274
+ "/v1/predictions",
275
+ json={"note": "DKA with blood glucose 580 and pH 7.1. Insulin drip started."},
276
+ )
277
+ pred_id = create.json()["data"]["id"]
278
+
279
+ response = client.delete(f"/v1/predictions/{pred_id}")
280
+ assert response.status_code == 204
281
+
282
+ def test_delete_nonexistent_returns_404(self, client):
283
+ """Trying to delete something that doesn't exist returns 404."""
284
+ response = client.delete("/v1/predictions/nonexistent-id")
285
+ assert response.status_code == 404
286
+
287
+ def test_delete_actually_removes_prediction(self, client):
288
+ """After deleting, the prediction should no longer be found."""
289
+ create = client.post(
290
+ "/v1/predictions",
291
+ json={
292
+ "note": "New onset atrial fibrillation with rapid ventricular response at 180 bpm."
293
+ },
294
+ )
295
+ pred_id = create.json()["data"]["id"]
296
+
297
+ client.delete(f"/v1/predictions/{pred_id}")
298
+
299
+ # Verify it's gone
300
+ response = client.get(f"/v1/predictions/{pred_id}")
301
+ assert response.status_code == 404
302
+
303
+
304
+ # =====================================================================
305
+ # Tests for GET /v1/model/info
306
+ # =====================================================================
307
+
308
+
309
+ class TestModelInfo:
310
+ """Tests for the model info endpoint."""
311
+
312
+ @skip_without_model
313
+ def test_model_info_returns_200(self, client):
314
+ """When model is loaded, info should return 200."""
315
+ response = client.get("/v1/model/info")
316
+ assert response.status_code == 200
317
+
318
+ @skip_without_model
319
+ def test_model_info_has_accuracy(self, client):
320
+ """Model info should include accuracy from training."""
321
+ response = client.get("/v1/model/info")
322
+ data = response.json()["data"]
323
+ assert "accuracy" in data
324
+
325
+
326
+ # =====================================================================
327
+ # YOUR TURN — Add Your Own Tests
328
+ # =====================================================================
329
+ #
330
+ # Challenge 1 (Easy):
331
+ # Write a test that creates 5 predictions and verifies the total
332
+ # count in the meta is correct.
333
+ #
334
+ # Challenge 2 (Medium):
335
+ # Write a test for double-delete: delete a prediction, then try to
336
+ # delete it again. What status code should the second delete return?
337
+ #
338
+ # Challenge 3 (Stretch):
339
+ # Write a parameterized test (using @pytest.mark.parametrize) that
340
+ # tests multiple clinical notes and verifies:
341
+ # - All urgent-sounding notes get "urgent"
342
+ # - All routine-sounding notes get "routine"
343
+ # This is a great way to build a test suite for your model!
lab_05_deploy/README.md ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 05 — Deploy Your API
2
+
3
+ > **Goal:** Deploy the prediction API so anyone on the internet can
4
+ > use it. Three options: Render, HuggingFace Spaces, or Docker.
5
+
6
+ > **Time:** ~30 minutes
7
+
8
+ > **Prerequisites:**
9
+ > [Lab 04 — Test the API](../lab_04_test_api/README.md)
10
+
11
+ ---
12
+
13
+ ## What You'll Learn
14
+
15
+ - How to deploy a FastAPI app to Render (free tier)
16
+ - How to deploy to HuggingFace Spaces via Docker
17
+ - How to run the API in Docker locally
18
+ - What CORS is and why it matters
19
+ - What a health check endpoint does
20
+
21
+ ---
22
+
23
+ ## What's Different in the Production App?
24
+
25
+ Open [app.py](app.py) and compare it to Lab 03's version. Key additions:
26
+
27
+ | Feature | Why It Matters |
28
+ |---|---|
29
+ | **CORS middleware** | Lets browsers (React, dashboards) call your API |
30
+ | **Demo mode** | API works even without a trained model — returns placeholder predictions |
31
+ | **Health check** (`/health`) | Hosting platforms ping this to know if your service is alive |
32
+ | **Root endpoint** (`/`) | Friendly landing page with links to docs |
33
+
34
+ ---
35
+
36
+ ## Option A: Deploy to Render (Recommended for Beginners)
37
+
38
+ [Render](https://render.com) is a cloud platform with a free tier —
39
+ perfect for learning.
40
+
41
+ ### Steps
42
+
43
+ 1. **Push your code to GitHub** (if you haven't already):
44
+ ```bash
45
+ git add -A
46
+ git commit -m "Ready for deployment"
47
+ git push origin main
48
+ ```
49
+
50
+ 2. **Go to** [render.com](https://render.com) and sign in with GitHub.
51
+
52
+ 3. **Click "New +" → "Web Service"**.
53
+
54
+ 4. **Connect your GitHub repo** (REST-API-Builder or API).
55
+
56
+ 5. Render will detect `render.yaml` automatically. Verify these
57
+ settings:
58
+ - **Build command:** `pip install uv && uv sync && python lab_02_train_model/train.py`
59
+ - **Start command:** `uvicorn lab_05_deploy.app:app --host 0.0.0.0 --port $PORT`
60
+
61
+ 6. **Click "Create Web Service"** and wait for the build (~2 min).
62
+
63
+ 7. **Visit your URL** — e.g. `https://rest-api-builder.onrender.com/docs`
64
+
65
+ > **Note:** The free tier spins down after 15 min of inactivity.
66
+ > The first request after idle takes ~30 seconds to cold-start.
67
+
68
+ ### How render.yaml Works
69
+
70
+ The [render.yaml](../render.yaml) file is a blueprint that tells Render:
71
+ - **buildCommand** — install dependencies AND train the model
72
+ - **startCommand** — run the production app
73
+ - **plan: free** — use the free tier
74
+
75
+ ---
76
+
77
+ ## Option B: Deploy to HuggingFace Spaces
78
+
79
+ [HuggingFace Spaces](https://huggingface.co/spaces) hosts Docker-based
80
+ apps for free.
81
+
82
+ ### Steps
83
+
84
+ 1. Go to [huggingface.co/spaces](https://huggingface.co/spaces) →
85
+ "Create new Space".
86
+
87
+ 2. Choose **Docker** as the SDK.
88
+
89
+ 3. Clone the Space repo locally and copy your project files into it.
90
+
91
+ 4. The [Dockerfile](../Dockerfile) is already configured for HF Spaces:
92
+ - Trains the model at build time
93
+ - Exposes port 7860 (HF Spaces requirement)
94
+
95
+ 5. Push to the Space and wait for the build.
96
+
97
+ 6. Your API will be live at
98
+ `https://huggingface.co/spaces/<your-username>/<space-name>`
99
+
100
+ ---
101
+
102
+ ## Option C: Run with Docker Locally
103
+
104
+ If you want to practice Docker before deploying, run the API in a
105
+ container on your own machine.
106
+
107
+ ### Steps
108
+
109
+ ```bash
110
+ # 1. Build the Docker image
111
+ # This installs dependencies AND trains the model
112
+ docker build -t rest-api-builder .
113
+
114
+ # 2. Run the container
115
+ # -p 7860:7860 maps container port to your machine
116
+ docker run -p 7860:7860 rest-api-builder
117
+
118
+ # 3. Visit the API
119
+ # http://localhost:7860/docs
120
+ ```
121
+
122
+ ### What the Dockerfile Does
123
+
124
+ ```dockerfile
125
+ FROM python:3.11-slim # Start with a clean Python image
126
+ RUN pip install uv # Install uv (fast package manager)
127
+ COPY pyproject.toml . # Copy deps first (cached layer)
128
+ COPY . . # Copy all project files
129
+ RUN uv sync --no-dev # Install production deps only
130
+ RUN python lab_02_train_model/train.py # Train model at build time
131
+ EXPOSE 7860 # Declare the port
132
+ CMD ["uvicorn", ...] # Start the server
133
+ ```
134
+
135
+ Key Docker concepts:
136
+ - **Image** — a snapshot of your app + all dependencies (like a template)
137
+ - **Container** — a running instance of an image (like a VM, but lighter)
138
+ - **Layer caching** — Docker reuses unchanged layers, so rebuilds are fast
139
+ - **EXPOSE** — documents the port; `-p` actually maps it
140
+
141
+ ### Useful Docker Commands
142
+
143
+ ```bash
144
+ # List running containers
145
+ docker ps
146
+
147
+ # Stop a container
148
+ docker stop <container-id>
149
+
150
+ # View container logs
151
+ docker logs <container-id>
152
+
153
+ # Remove the image (to rebuild from scratch)
154
+ docker rmi rest-api-builder
155
+ ```
156
+
157
+ ---
158
+
159
+ ## Verify Your Deployment
160
+
161
+ Regardless of which option you chose, test these endpoints:
162
+
163
+ ```bash
164
+ # Replace URL with your deployment URL
165
+ URL="http://localhost:7860" # or your Render/HF URL
166
+
167
+ # Health check
168
+ curl $URL/health
169
+
170
+ # Interactive docs
171
+ # Open in browser: $URL/docs
172
+
173
+ # Create a prediction
174
+ curl -X POST $URL/v1/predictions \
175
+ -H "Content-Type: application/json" \
176
+ -d '{"note": "Acute chest pain with ST-elevation and troponin rise"}'
177
+
178
+ # List predictions
179
+ curl $URL/v1/predictions
180
+
181
+ # Model info
182
+ curl $URL/v1/model/info
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Understanding CORS
188
+
189
+ When you open a React dashboard at `http://localhost:3000` and it
190
+ tries to call your API at `http://localhost:7860`, the browser blocks
191
+ it by default. This is **Cross-Origin Resource Sharing (CORS)**.
192
+
193
+ Our app.py adds CORS middleware that says "allow requests from
194
+ anywhere." In production, you would restrict this to your actual
195
+ frontend domain:
196
+
197
+ ```python
198
+ app.add_middleware(
199
+ CORSMiddleware,
200
+ allow_origins=["https://my-dashboard.example.com"],
201
+ ...
202
+ )
203
+ ```
204
+
205
+ ---
206
+
207
+ ## ✅ Done When
208
+
209
+ - [ ] Your API is deployed and accessible via a public URL
210
+ (OR running in Docker locally)
211
+ - [ ] The `/health` endpoint returns `{"status": "healthy"}`
212
+ - [ ] You can create a prediction via `/docs`
213
+ - [ ] You understand why CORS middleware is needed
214
+ - [ ] You can explain what the Dockerfile does step by step
215
+
216
+ ---
217
+
218
+ ## 🎉 Congratulations!
219
+
220
+ You've completed the entire REST-API-Builder tutorial!
221
+
222
+ Here's what you've accomplished:
223
+
224
+ 1. **Lab 00** — Learned REST fundamentals, HTTP verbs, and status codes
225
+ 2. **Lab 01** — Built your first CRUD API with FastAPI
226
+ 3. **Lab 02** — Trained a clinical urgency classifier
227
+ 4. **Lab 03** — Exposed the model as a REST API
228
+ 5. **Lab 04** — Wrote automated tests with pytest
229
+ 6. **Lab 05** — Deployed to the cloud (or Docker)
230
+
231
+ You now have the skills to take **any** machine learning model and
232
+ serve it as a production-ready REST API.
233
+
234
+ ### What to Explore Next
235
+
236
+ - Add authentication (API keys or OAuth)
237
+ - Connect to a real database (PostgreSQL, MongoDB)
238
+ - Add logging and monitoring
239
+ - Try deploying with CI/CD (see the
240
+ [ci-cd-template](https://github.com/po-DRA/ci-cd-template))
241
+ - Explore the [API Learning Roadmap](https://bytebytego.com/guides/the-ultimate-api-learning-roadmap/)
lab_05_deploy/__init__.py ADDED
File without changes
lab_05_deploy/app.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Lab 05 — Production-Ready Deployment App
3
+ =========================================
4
+ This is the deployment-ready version of the prediction API. It adds:
5
+ - CORS middleware (so browsers can call the API)
6
+ - Graceful demo mode (works even without a trained model)
7
+ - Health check endpoint (required by most hosting platforms)
8
+
9
+ Deployment options:
10
+ 1. Render: Push to GitHub → connect repo in Render dashboard
11
+ render.yaml handles build + start automatically
12
+ 2. HuggingFace Spaces: Push to a HF Space → Dockerfile handles it
13
+ 3. Docker: docker build -t rest-api-builder . && docker run -p 7860:7860 rest-api-builder
14
+
15
+ How to run locally:
16
+ uvicorn lab_05_deploy.app:app --reload --port 7860
17
+
18
+ Reference:
19
+ - Deploy NLP with FastAPI + HuggingFace:
20
+ https://towardsdatascience.com/deploy-nlp-models-with-fastapi-streamlit-and-hugging-face/
21
+ - Deploying ML models with FastAPI:
22
+ https://www.analyticsvidhya.com/blog/2022/09/deploying-ml-models-using-fastapi/
23
+ """
24
+
25
+ import json
26
+ import os
27
+ from contextlib import asynccontextmanager
28
+ from datetime import UTC, datetime
29
+ from uuid import uuid4
30
+
31
+ import joblib
32
+ from fastapi import FastAPI, HTTPException, Query
33
+ from fastapi.middleware.cors import CORSMiddleware
34
+ from pydantic import BaseModel, Field
35
+
36
+ # ── Paths ───────────────────────────────────────────────────────────
37
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
38
+ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
39
+ MODEL_PATH = os.path.join(PROJECT_ROOT, "models", "urgency_classifier.joblib")
40
+ META_PATH = os.path.join(PROJECT_ROOT, "models", "model_meta.json")
41
+
42
+ # ── Global state ────────────────────────────────────────────────────
43
+ model = None
44
+ model_meta = None
45
+ predictions_db: dict[str, dict] = {}
46
+
47
+
48
+ # ── Lifespan ────────────────────────────────────────────────────────
49
+
50
+
51
+ @asynccontextmanager
52
+ async def lifespan(app: FastAPI):
53
+ """Load model at startup. If not available, enter demo mode."""
54
+ global model, model_meta
55
+
56
+ if os.path.exists(MODEL_PATH):
57
+ model = joblib.load(MODEL_PATH)
58
+ print(f"[OK] Model loaded from {MODEL_PATH}")
59
+ else:
60
+ print("[WARN] Model not found — running in DEMO MODE")
61
+ print(" Predictions will return a placeholder response.")
62
+ print(" To use real predictions, run: python lab_02_train_model/train.py")
63
+
64
+ if os.path.exists(META_PATH):
65
+ with open(META_PATH) as f:
66
+ model_meta = json.load(f)
67
+
68
+ yield
69
+
70
+ model = None
71
+ model_meta = None
72
+
73
+
74
+ # ── App ─────────────────────────────────────────────────────────────
75
+ app = FastAPI(
76
+ title="Clinical Urgency Prediction API",
77
+ description=(
78
+ "Predicts whether a clinical note is **urgent** or **routine**. "
79
+ "Built as part of the REST-API-Builder tutorial."
80
+ ),
81
+ version="1.0.0",
82
+ lifespan=lifespan,
83
+ )
84
+
85
+ # ── CORS Middleware ─────────────────────────────────────────────────
86
+ # CORS (Cross-Origin Resource Sharing) controls which websites can
87
+ # call your API from a browser.
88
+ #
89
+ # Without CORS, a React app at http://localhost:3000 would be BLOCKED
90
+ # from calling your API at http://localhost:7860 — browsers enforce
91
+ # this for security.
92
+ #
93
+ # In production, replace "*" with your actual frontend domain(s).
94
+ app.add_middleware(
95
+ CORSMiddleware,
96
+ allow_origins=["*"], # Which domains can call the API
97
+ allow_credentials=True,
98
+ allow_methods=["*"], # Which HTTP methods are allowed
99
+ allow_headers=["*"], # Which headers can be sent
100
+ )
101
+
102
+
103
+ # ── Pydantic models ────────────────────────────────────────────────
104
+
105
+
106
+ class PredictionRequest(BaseModel):
107
+ note: str = Field(
108
+ ...,
109
+ min_length=10,
110
+ json_schema_extra={
111
+ "example": "Patient presents with acute chest pain and shortness of breath."
112
+ },
113
+ )
114
+
115
+
116
+ # ── Health check ────────────────────────────────────────────────────
117
+ # Every production API needs a health check endpoint.
118
+ # Hosting platforms (Render, AWS, k8s) ping this endpoint to know
119
+ # if your service is alive. If it returns non-200, they restart it.
120
+
121
+
122
+ @app.get("/health", status_code=200, tags=["System"])
123
+ def health_check():
124
+ """Health check endpoint for hosting platforms."""
125
+ return {
126
+ "status": "healthy",
127
+ "model_loaded": model is not None,
128
+ "timestamp": datetime.now(UTC).isoformat(),
129
+ }
130
+
131
+
132
+ # ── Root endpoint ──────────────────────────────────────────────────
133
+
134
+
135
+ @app.get("/", status_code=200, tags=["System"])
136
+ def root():
137
+ """Welcome page with links to docs and endpoints."""
138
+ return {
139
+ "message": "Clinical Urgency Prediction API",
140
+ "docs": "/docs",
141
+ "health": "/health",
142
+ "endpoints": {
143
+ "predictions": "/v1/predictions",
144
+ "model_info": "/v1/model/info",
145
+ },
146
+ }
147
+
148
+
149
+ # ── Predictions ─────────────────────────────────────────────────────
150
+
151
+
152
+ @app.post("/v1/predictions", status_code=201, tags=["Predictions"])
153
+ def create_prediction(request: PredictionRequest):
154
+ """Classify a clinical note as urgent or routine."""
155
+
156
+ pred_id = str(uuid4())
157
+
158
+ if model is not None:
159
+ # Real prediction
160
+ prediction = model.predict([request.note])[0]
161
+ probabilities = model.predict_proba([request.note])[0]
162
+ confidence = float(max(probabilities))
163
+ else:
164
+ # Demo mode — return a placeholder so the API is still usable
165
+ prediction = "demo"
166
+ confidence = 0.0
167
+
168
+ record = {
169
+ "id": pred_id,
170
+ "note": request.note,
171
+ "prediction": prediction,
172
+ "confidence": round(confidence, 4),
173
+ "created_at": datetime.now(UTC).isoformat(),
174
+ }
175
+ predictions_db[pred_id] = record
176
+
177
+ return {
178
+ "data": record,
179
+ "meta": {
180
+ "model_loaded": model is not None,
181
+ "model_version": model_meta.get("trained_at", "unknown") if model_meta else "demo",
182
+ },
183
+ }
184
+
185
+
186
+ @app.get("/v1/predictions", status_code=200, tags=["Predictions"])
187
+ def list_predictions(
188
+ prediction: str | None = Query(None, description="Filter by label"),
189
+ limit: int = Query(10, ge=1, le=100),
190
+ offset: int = Query(0, ge=0),
191
+ ):
192
+ """List stored predictions with filtering and pagination."""
193
+ results = list(predictions_db.values())
194
+
195
+ if prediction:
196
+ results = [r for r in results if r["prediction"] == prediction]
197
+
198
+ total = len(results)
199
+ results = results[offset : offset + limit]
200
+
201
+ return {
202
+ "data": results,
203
+ "meta": {"total": total, "limit": limit, "offset": offset},
204
+ }
205
+
206
+
207
+ @app.get("/v1/predictions/{prediction_id}", status_code=200, tags=["Predictions"])
208
+ def get_prediction(prediction_id: str):
209
+ """Get a specific prediction by ID."""
210
+ if prediction_id not in predictions_db:
211
+ raise HTTPException(status_code=404, detail="Prediction not found")
212
+ return {"data": predictions_db[prediction_id]}
213
+
214
+
215
+ @app.delete("/v1/predictions/{prediction_id}", status_code=204, tags=["Predictions"])
216
+ def delete_prediction(prediction_id: str):
217
+ """Delete a prediction."""
218
+ if prediction_id not in predictions_db:
219
+ raise HTTPException(status_code=404, detail="Prediction not found")
220
+ del predictions_db[prediction_id]
221
+
222
+
223
+ @app.get("/v1/model/info", status_code=200, tags=["Model"])
224
+ def get_model_info():
225
+ """Return model metadata."""
226
+ if model_meta is None:
227
+ return {
228
+ "data": {"status": "demo mode — no model loaded"},
229
+ "meta": {"model_loaded": False},
230
+ }
231
+ return {
232
+ "data": model_meta,
233
+ "meta": {"model_loaded": model is not None},
234
+ }
models/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # models/
2
+
3
+ This folder stores trained model artifacts. The files are generated
4
+ when you run `lab_02_train_model/train.py` and are **not** checked
5
+ into Git (see `.gitignore`).
6
+
7
+ After training you will see:
8
+
9
+ | File | What it is |
10
+ |---|---|
11
+ | `urgency_classifier.joblib` | The trained scikit-learn Pipeline (TF-IDF + Logistic Regression) |
12
+ | `model_meta.json` | Metadata — accuracy, training date, feature count, class labels |
pyproject.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # pyproject.toml — Single config for deps, tools, and metadata
3
+ # ============================================================
4
+ # Modern Python projects use pyproject.toml instead of separate
5
+ # requirements.txt, setup.py, setup.cfg, .flake8, pyproject.toml, etc.
6
+ #
7
+ # Install with: uv sync
8
+ # Or with pip: pip install -e ".[dev]"
9
+ # ============================================================
10
+
11
+ [project]
12
+ name = "rest-api-builder"
13
+ version = "1.0.0"
14
+ description = "Hands-on tutorial: build, test, and deploy a REST API serving an ML model"
15
+ readme = "README.md"
16
+ requires-python = ">=3.11"
17
+
18
+ # --- Runtime dependencies ---
19
+ dependencies = [
20
+ "fastapi>=0.115.0",
21
+ "uvicorn[standard]>=0.30.0",
22
+ "scikit-learn>=1.5.1",
23
+ "joblib>=1.4.2",
24
+ "pandas>=2.2.2",
25
+ "python-multipart>=0.0.9",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ # Dev dependencies — install with: uv sync --extra dev
30
+ dev = [
31
+ "pytest>=8.3.2",
32
+ "httpx>=0.27.0", # needed by FastAPI TestClient
33
+ "ruff>=0.6.0", # linter + formatter (replaces flake8, black, isort)
34
+ ]
35
+
36
+ # ── Ruff configuration ─────────────────────────────────────────────
37
+ # Ruff is a blazing-fast Python linter and formatter written in Rust.
38
+ # It replaces flake8, black, isort, and more — all in one tool.
39
+ #
40
+ # Run linter: ruff check .
41
+ # Auto-fix: ruff check . --fix
42
+ # Format code: ruff format .
43
+
44
+ [tool.ruff]
45
+ target-version = "py311"
46
+ line-length = 100
47
+
48
+ [tool.ruff.lint]
49
+ select = [
50
+ "E", # pycodestyle errors
51
+ "W", # pycodestyle warnings
52
+ "F", # pyflakes
53
+ "I", # isort (import sorting)
54
+ "UP", # pyupgrade (modern Python syntax)
55
+ "B", # flake8-bugbear (common bugs)
56
+ ]
57
+ ignore = [
58
+ "E501", # line too long — formatter handles this
59
+ ]
60
+
61
+ [tool.ruff.format]
62
+ quote-style = "double"
63
+
64
+ # ── Pytest configuration ───────────────────────────────────────────
65
+ [tool.pytest.ini_options]
66
+ testpaths = ["lab_04_test_api"]
67
+ pythonpath = ["."] # ensures lab_03_expose_model is importable
68
+ addopts = "-v"
render.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # render.yaml — Render deployment blueprint
3
+ # ============================================================
4
+ # This file tells Render how to build and run the API.
5
+ # Render reads this automatically when you connect the repo.
6
+ #
7
+ # Key decisions:
8
+ # - buildCommand trains the model FIRST, then installs deps
9
+ # - startCommand runs the production app from lab_05_deploy/
10
+ # - The free tier is perfect for learning / demos
11
+ # ============================================================
12
+
13
+ services:
14
+ - type: web
15
+ name: rest-api-builder
16
+ runtime: python
17
+ buildCommand: |
18
+ pip install uv && uv sync && python lab_02_train_model/train.py
19
+ startCommand: uvicorn lab_05_deploy.app:app --host 0.0.0.0 --port $PORT
20
+ envVars:
21
+ - key: PYTHON_VERSION
22
+ value: "3.11"
23
+ plan: free
requirements.txt DELETED
@@ -1,9 +0,0 @@
1
- fastapi==0.111.0
2
- uvicorn[standard]==0.29.0
3
- transformers==4.41.0
4
- torch==2.3.0
5
- streamlit==1.35.0
6
- httpx==0.27.0
7
- python-multipart==0.0.9
8
- pydantic==2.7.1
9
- slowapi==0.1.9
 
 
 
 
 
 
 
 
 
 
solutions/lab_00_answers.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 00 — Quiz Answers
2
+
3
+ 1. **GET** — retrieving data always uses GET.
4
+
5
+ 2. **201 Created** — POST that creates a new resource should return 201,
6
+ not 200.
7
+
8
+ 3. **204 No Content** — the resource is gone; there is nothing to send
9
+ back.
10
+
11
+ 4. Two problems:
12
+ - It uses a verb (`get`) — the HTTP method already says GET.
13
+ - It mixes filtering into the path — it should be
14
+ `GET /v1/patients?status=active`.
15
+
16
+ 5. **404 Not Found** — the resource does not exist.
17
+
18
+ 6. **Path parameter** — identifies a specific resource:
19
+ `/v1/patients/42` (patient with ID 42).
20
+ **Query parameter** — filters or paginates a collection:
21
+ `/v1/patients?status=active` (only active patients).
22
+
23
+ 7. Statelessness means every request carries all the information the
24
+ server needs. This lets you run multiple copies of the server
25
+ behind a load balancer — any copy can handle any request because
26
+ none of them need to "remember" previous requests.
27
+
28
+ 8. Any two of:
29
+ - Non-Python users (JavaScript, mobile apps) can call an API but
30
+ can't `pip install`.
31
+ - You deploy once and everyone gets the latest version instantly —
32
+ no asking every user to upgrade.
33
+ - You can add access control (API keys, rate limits, audit logs).
34
+ - Data stays on the server, so you control security and compliance.
35
+
36
+ 9. The JSON was syntactically valid, but the *values* didn't make
37
+ sense (e.g. a negative age, or a missing required field). It's a
38
+ **client error** — the server understood the shape but not the
39
+ content.
40
+
41
+ 10. Any two of:
42
+ - Interactive Swagger UI (`/docs`)
43
+ - ReDoc documentation (`/redoc`)
44
+ - The raw OpenAPI JSON spec (`/openapi.json`)
45
+ - Client code generation
solutions/lab_01_challenge3.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lab 01 — Challenge 3: Search Endpoint
2
+
3
+ ## Why POST for Search?
4
+
5
+ HTTP GET requests **should not have a request body** (some servers
6
+ ignore it). When the search criteria are too complex for query
7
+ parameters (e.g. nested filters, free-text queries), using POST with a
8
+ JSON body is a common REST pattern.
9
+
10
+ ## Solution
11
+
12
+ ```python
13
+ class SearchRequest(BaseModel):
14
+ query: str = Field(..., min_length=1, example="diabetes")
15
+
16
+
17
+ @app.post("/v1/patients/search", status_code=200, tags=["Patients"])
18
+ def search_patients(search: SearchRequest):
19
+ """Search patients by name or condition (case-insensitive)."""
20
+ q = search.query.lower()
21
+ results = [
22
+ p for p in patients_db.values()
23
+ if q in p["name"].lower() or q in p["condition"].lower()
24
+ ]
25
+ return {"data": results, "meta": {"total": len(results)}}
26
+ ```
27
+
28
+ Note: We return `200 OK` (not `201`) because we are not *creating*
29
+ anything — we are performing a search that returns results.
step_00_concepts/README.md DELETED
@@ -1,131 +0,0 @@
1
- # 🧠 Step 0 — What Is an API, and Why Does a Researcher Need One?
2
-
3
- > ⏱ **Time: ~10 minutes** | No code yet — just the mental model.
4
-
5
- ---
6
-
7
- ## The One Analogy You Need
8
-
9
- Imagine you're a lab technician. You don't need to know how an MRI machine is built — you just put a patient in, press a button, and get results back.
10
-
11
- **An API is that button.**
12
-
13
- An API (**A**pplication **P**rogramming **I**nterface) is a contract between:
14
- - A **caller** — the one asking for something ("classify this clinical note")
15
- - A **service** — the one doing the work (your ML model)
16
-
17
- The caller doesn't care *how* the model works internally. It just sends a request and gets an answer.
18
-
19
- ---
20
-
21
- ## Why Wrap an ML Model in an API?
22
-
23
- | Without an API | With an API |
24
- |---|---|
25
- | Run a Python script manually | Any tool, app, or colleague can call your model |
26
- | Share a `.pkl` file and hope they have the right Python version | One URL works from anywhere |
27
- | Results are one-off | Results are on-demand, any time |
28
- | Only you can use it | Clinicians, dashboards, EHRs can all integrate it |
29
-
30
- > 💡 **For medical research specifically:** You can build a model once, then let a hospital dashboard, a mobile app, or a collaborator's R script all call the *same* model via its API — no Python needed on their end.
31
-
32
- ---
33
-
34
- ## The API Lifecycle (In 5 Steps)
35
-
36
- ```
37
- ┌─────────────────────────────────────────────────────────────┐
38
- │ │
39
- │ 1. DESIGN What does this API do? What inputs/outputs?│
40
- │ ↓ │
41
- │ 2. BUILD Write the Python/FastAPI code │
42
- │ ↓ │
43
- │ 3. TEST Does it respond correctly? │
44
- │ ↓ │
45
- │ 4. DOCUMENT Others need to know how to call it │
46
- │ ↓ │
47
- │ 5. DEPLOY Put it on a server so anyone can reach it │
48
- │ │
49
- └─────────────────────────────────────────────────────────────┘
50
- ```
51
-
52
- We will do **all 5 steps** in this tutorial.
53
-
54
- ---
55
-
56
- ## What Projects Are Good API Candidates?
57
-
58
- Ask yourself: **"Would someone else want to call this automatically?"**
59
-
60
- ### ✅ Great for APIs:
61
- - **NLP on clinical notes** — extract diagnoses, medications, SOAP summaries
62
- - **Image classification** — pathology slides, X-ray triage
63
- - **Risk scoring** — "give me a readmission risk score for this patient"
64
- - **Drug interaction checker** — lookup + ML together
65
- - **Literature search summarizer** — wrap PubMed + an LLM
66
-
67
- ### ❌ Less ideal for APIs (for now):
68
- - One-off exploratory analysis (just use a notebook)
69
- - Giant batch jobs that take hours (use a queue instead — though APIs *can* trigger these!)
70
-
71
- ---
72
-
73
- ## The Big Question: Does the Model Run Live or Pre-Computed?
74
-
75
- This is the most important architecture decision:
76
-
77
- ```
78
- ┌──────────────────────────────────────────────────────────┐
79
- │ │
80
- │ OPTION A: Live Inference (model runs on each request) │
81
- │ ┌──────────┐ Request ┌──────────┐ Result │
82
- │ │ Caller │ ──────────► │ Model │ ────────► JSON │
83
- │ └──────────┘ └──────────┘ │
84
- │ ✅ Always fresh ❌ Slower, needs GPU/RAM │
85
- │ │
86
- │ OPTION B: Pre-computed (model ran offline, API looks up)│
87
- │ ┌──────────┐ Request ┌──────────┐ Result │
88
- │ │ Caller │ ──────────► │ Cache / │ ────────► JSON │
89
- │ └──────────┘ │ DB │ │
90
- │ ✅ Blazing fast ❌ Can't handle new/unseen inputs │
91
- │ │
92
- │ OPTION C: Background Tasks (API accepts job, runs async)│
93
- │ ┌──────────┐ Submit ┌──────────┐ │
94
- │ │ Caller │ ─────────► │ Queue │ → Model runs... │
95
- │ └──────────┘ └──────────┘ │
96
- │ �� Later: "Is job 42 done?" ↓ │
97
- │ └──────────────────────────── Results ready ✅ │
98
- │ ✅ Best of both ⚠️ More complex to build │
99
- │ │
100
- └──────────────────────────────────────────────────────────┘
101
- ```
102
-
103
- **In this tutorial you will build all three.** By the end, you'll know exactly when to use each pattern.
104
-
105
- ---
106
-
107
- ## Key Terms Cheatsheet
108
-
109
- | Term | Plain English |
110
- |------|--------------|
111
- | **Endpoint** | A specific URL that does one thing, e.g. `/classify` |
112
- | **Request** | What you send to the API (the question) |
113
- | **Response** | What comes back (the answer), usually JSON |
114
- | **GET** | "Give me information" — used for lookups |
115
- | **POST** | "Here's some data, process it" — used for predictions |
116
- | **JSON** | The universal data format APIs use to talk |
117
- | **OpenAPI/Swagger** | Auto-generated interactive docs for your API |
118
- | **FastAPI** | The Python framework we'll use — it's fast, modern, and auto-documents |
119
-
120
- ---
121
-
122
- ## 📚 Reference Links
123
-
124
- - [What is an API?](https://www.ibm.com/topics/api)
125
- - [API Lifecycle explained](https://swagger.io/blog/api-development/stages-of-the-api-lifecycle/)
126
- - [OpenAPI Specification](https://swagger.io/specification/)
127
- - [FastAPI Official Docs](https://fastapi.tiangolo.com/)
128
-
129
- ---
130
-
131
- ➡️ **Ready? Move to [Step 1 →](../step_01_hello_api/README.md)**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_01_hello_api/README.md DELETED
@@ -1,90 +0,0 @@
1
- # 🚀 Step 1 — Hello API: Your First FastAPI Server
2
-
3
- > ⏱ **Time: ~10 minutes** | First working API in under 5 minutes
4
-
5
- ---
6
-
7
- ## What You'll Learn
8
-
9
- - How to start a FastAPI server
10
- - The difference between GET and POST
11
- - How FastAPI auto-generates documentation (this is magic ✨)
12
- - The exact pattern every ML API will follow
13
-
14
- ---
15
-
16
- ## ▶️ Start It (in GitHub Codespaces or locally)
17
-
18
- ```bash
19
- cd step_01_hello_api
20
- uvicorn app:app --reload --port 8000
21
- ```
22
-
23
- You'll see:
24
- ```
25
- INFO: Uvicorn running on http://127.0.0.1:8000
26
- INFO: Application startup complete.
27
- ```
28
-
29
- ---
30
-
31
- ## 🔍 Explore These URLs
32
-
33
- | URL | What it does |
34
- |-----|-------------|
35
- | `http://localhost:8000/` | Root — the "heartbeat" |
36
- | `http://localhost:8000/docs` | **Auto-generated Swagger UI** — try every endpoint here! |
37
- | `http://localhost:8000/patient/P001` | URL parameter example |
38
- | `http://localhost:8000/search?keyword=diabetes` | Query parameter example |
39
-
40
- ---
41
-
42
- ## 🧪 Test Your First POST Request
43
-
44
- In the Swagger UI (`/docs`), click on **POST /analyze**, then **"Try it out"** and paste:
45
-
46
- ```json
47
- {
48
- "note_text": "Patient presents with severe chest pain and shortness of breath",
49
- "patient_id": "P001"
50
- }
51
- ```
52
-
53
- You'll get back a JSON response. This is **exactly** the pattern your ML model will use.
54
-
55
- ---
56
-
57
- ## 💡 Key Insight: OpenAPI is Built In
58
-
59
- FastAPI automatically generates an **OpenAPI spec** for you. The `/docs` page IS the documentation — you don't write it separately. Every parameter, type, and example is extracted from your Python code.
60
-
61
- This means: **your code is your documentation.** No extra work.
62
-
63
- ---
64
-
65
- ## 🔬 What's Happening Inside `app.py`
66
-
67
- ```
68
- FastAPI app
69
- │
70
- ├── GET / ← No input, returns status
71
- ├── GET /patient/{id} ← Input in URL path
72
- ├── GET /search?keyword=... ← Input as query parameter
73
- └── POST /analyze ← Input as JSON body ← THIS IS YOUR ML PATTERN
74
- ```
75
-
76
- The `POST /analyze` endpoint is the template for every ML prediction endpoint you'll ever build.
77
-
78
- ---
79
-
80
- ## ✏️ Challenge (Optional)
81
-
82
- Open `app.py` and add a new endpoint at the bottom. Ideas:
83
- - `GET /medications/{drug_name}` — return fake drug info
84
- - `POST /icd-lookup` — accept a symptom description, return a fake ICD-10 code
85
-
86
- After saving, the server reloads automatically (that's what `--reload` does). Check `/docs` — your new endpoint appears immediately.
87
-
88
- ---
89
-
90
- ➡️ **Next: [Step 2 — Real Medical NLP Model →](../step_02_medical_api/README.md)**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_01_hello_api/app.py DELETED
@@ -1,121 +0,0 @@
1
- """
2
- Step 1 — Hello API
3
- ==================
4
- Your first FastAPI server. No ML yet — just understanding the structure.
5
-
6
- Run it:
7
- uvicorn app:app --reload --port 8000
8
-
9
- Then open:
10
- http://localhost:8000 ← "Hello" response
11
- http://localhost:8000/docs ← Interactive Swagger UI (FREE documentation!)
12
- http://localhost:8000/patient/P001 ← Try a URL parameter
13
- """
14
-
15
- from fastapi import FastAPI
16
- from pydantic import BaseModel
17
- from datetime import datetime
18
-
19
- # ── 1. Create the app ──────────────────────────────────────────────────────────
20
- app = FastAPI(
21
- title="Hello Medical API",
22
- description="My first API — understanding the basics before adding ML",
23
- version="1.0.0",
24
- )
25
-
26
-
27
- # ── 2. The simplest possible endpoint ─────────────────────────────────────────
28
- @app.get("/")
29
- def root():
30
- """
31
- A GET endpoint — caller asks, we return info.
32
- No input needed, just a heartbeat.
33
- """
34
- return {
35
- "message": "Welcome to the Medical Research API 🏥",
36
- "status": "running",
37
- "timestamp": datetime.now().isoformat(),
38
- }
39
-
40
-
41
- # ── 3. URL parameters — pass data in the URL ───────────────────────────────────
42
- @app.get("/patient/{patient_id}")
43
- def get_patient(patient_id: str):
44
- """
45
- URL parameter: the patient_id comes from the URL itself.
46
- Try: GET /patient/P001
47
- """
48
- # Simulated — replace with real DB lookup
49
- fake_db = {
50
- "P001": {"name": "Alice", "age": 45, "condition": "hypertension"},
51
- "P002": {"name": "Bob", "age": 62, "condition": "diabetes"},
52
- }
53
- if patient_id in fake_db:
54
- return {"patient_id": patient_id, "data": fake_db[patient_id]}
55
- return {"error": f"Patient {patient_id} not found"}, 404
56
-
57
-
58
- # ── 4. Query parameters — optional filters after the ? ─────────────────────────
59
- @app.get("/search")
60
- def search_notes(keyword: str, limit: int = 5):
61
- """
62
- Query parameters come after the ?: /search?keyword=diabetes&limit=3
63
- 'limit' has a default value of 5 — it's optional.
64
- """
65
- fake_notes = [
66
- "Patient presents with type 2 diabetes and fatigue",
67
- "Diabetes mellitus, well-controlled on metformin",
68
- "Hypertension noted, diabetes screening recommended",
69
- "No diabetes, normal blood sugar levels",
70
- "Post-op diabetes management required",
71
- "Diabetes follow-up: A1C levels reviewed",
72
- ]
73
- matches = [n for n in fake_notes if keyword.lower() in n.lower()]
74
- return {
75
- "keyword": keyword,
76
- "results": matches[:limit],
77
- "count": len(matches[:limit]),
78
- }
79
-
80
-
81
- # ── 5. POST with a body — the ML pattern ──────────────────────────────────────
82
-
83
- class ClinicalNote(BaseModel):
84
- """
85
- Pydantic model = the shape of data we expect.
86
- FastAPI validates this automatically — bad data = clear error message.
87
- """
88
- note_text: str
89
- patient_id: str | None = None # Optional field
90
-
91
-
92
- @app.post("/analyze")
93
- def analyze_note(note: ClinicalNote):
94
- """
95
- POST endpoint — caller sends data in the body (JSON).
96
- This is the pattern you'll use for ML predictions.
97
-
98
- Try sending:
99
- {
100
- "note_text": "Patient has severe chest pain and shortness of breath",
101
- "patient_id": "P001"
102
- }
103
- """
104
- # Placeholder — in Step 2 we replace this with a real model
105
- word_count = len(note.note_text.split())
106
- has_urgent = any(word in note.note_text.lower()
107
- for word in ["severe", "emergency", "critical", "urgent"])
108
-
109
- return {
110
- "received": note.note_text,
111
- "word_count": word_count,
112
- "flagged_urgent": has_urgent,
113
- "note": "🔧 Real ML classification coming in Step 2!",
114
- }
115
-
116
-
117
- # ── CHALLENGE: Add your own endpoint below! ────────────────────────────────────
118
- # Ideas:
119
- # - GET /medications/{drug_name} → return fake drug info
120
- # - POST /icd-code → accept a description, return a fake ICD code
121
- # Try it and check http://localhost:8000/docs to see it appear automatically!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_02_medical_api/README.md DELETED
@@ -1,142 +0,0 @@
1
- # 🧬 Step 2 — Real Medical NLP Model
2
-
3
- > ⏱ **Time: ~15 minutes** | First real ML predictions
4
-
5
- ---
6
-
7
- ## What You'll Build
8
-
9
- A running API that extracts **diseases, drugs, genes** from clinical notes and classifies **urgency** — using real Hugging Face transformer models.
10
-
11
- ---
12
-
13
- ## ▶️ Start the Server
14
-
15
- ```bash
16
- cd step_02_medical_api
17
- uvicorn app:app --reload --port 8000
18
- ```
19
-
20
- > ⚠️ **First run**: The model downloads ~500MB from Hugging Face. This takes 1–3 minutes. Every run after that is instant (it's cached).
21
- >
22
- > If you're offline or in a hurry: the server falls back to **demo mode** and returns fake-but-correctly-structured results.
23
-
24
- ---
25
-
26
- ## 🔑 The Key Concept: Load Once, Serve Many
27
-
28
- ```python
29
- # ✅ THIS — model loads once when server starts
30
- ner_pipeline = pipeline("ner", model="d4data/biomedical-ner-all")
31
-
32
- @app.post("/extract-entities")
33
- def extract_entities(note):
34
- return ner_pipeline(note.text) # Model already in memory!
35
- ```
36
-
37
- ```python
38
- # ❌ NOT THIS — would reload the model on every request (30s wait!)
39
- @app.post("/extract-entities")
40
- def extract_entities(note):
41
- ner_pipeline = pipeline("ner", model="...") # Reloads every time!
42
- return ner_pipeline(note.text)
43
- ```
44
-
45
- This is the most important optimization for ML APIs.
46
-
47
- ---
48
-
49
- ## 🧪 Try These Examples
50
-
51
- Open `http://localhost:8000/docs` and test **POST /extract-entities** with:
52
-
53
- ### Example 1 — Cardiology note
54
- ```json
55
- {
56
- "text": "72-year-old male with acute myocardial infarction. On aspirin 100mg, atorvastatin 40mg. Family history of BRCA2 mutation.",
57
- "patient_id": "P001"
58
- }
59
- ```
60
-
61
- ### Example 2 — Oncology note
62
- ```json
63
- {
64
- "text": "Stage III colorectal cancer. Initiating FOLFOX chemotherapy. KRAS wild-type, MSI-H status confirmed.",
65
- "patient_id": "P002"
66
- }
67
- ```
68
-
69
- ### Example 3 — Emergency note (urgency test)
70
- ```json
71
- {
72
- "text": "Patient unresponsive, BP 60/40, suspected septic shock. Immediate ICU transfer required.",
73
- "patient_id": "P003"
74
- }
75
- ```
76
-
77
- ---
78
-
79
- ## 💡 Zero-Shot Classification Explained
80
-
81
- The `/classify-urgency` endpoint uses **zero-shot classification** — meaning the model was never trained on medical urgency labels. It reasons from general language understanding.
82
-
83
- ```python
84
- urgency_labels = [
85
- "life-threatening emergency",
86
- "urgent - needs attention within hours",
87
- "routine - can wait for next appointment",
88
- ]
89
- result = classifier(note.text, candidate_labels=urgency_labels)
90
- ```
91
-
92
- **You can change these labels to anything** — no retraining needed! This is incredibly powerful for rapid prototyping before you have labeled training data.
93
-
94
- ---
95
-
96
- ## 📊 What the Response Looks Like
97
-
98
- ```json
99
- {
100
- "patient_id": "P001",
101
- "entities": [
102
- {"entity_type": "Disease", "text": "myocardial infarction", "confidence": 0.98},
103
- {"entity_type": "Chemical", "text": "aspirin", "confidence": 0.96},
104
- {"entity_type": "Gene", "text": "BRCA2", "confidence": 0.93}
105
- ],
106
- "entity_summary": {
107
- "Disease": ["myocardial infarction"],
108
- "Chemical": ["aspirin", "atorvastatin"],
109
- "Gene": ["BRCA2"]
110
- },
111
- "processing_time_ms": 245.3,
112
- "model_used": "d4data/biomedical-ner-all"
113
- }
114
- ```
115
-
116
- ---
117
-
118
- ## 🔬 Other Hugging Face Models to Try
119
-
120
- Swap the model name in `app.py`:
121
-
122
- | Task | Model | Use Case |
123
- |------|-------|----------|
124
- | NER | `allenai/scibert_scivocab_uncased` | Scientific text |
125
- | NER | `sultan/BioM-ELECTRA-Large-SQuAD2` | Biomedical Q&A |
126
- | Classification | Any `facebook/bart-large-mnli` | Zero-shot triage |
127
- | Summarization | `Falconsai/medical_summarization` | Note summarization |
128
- | Translation | `Helsinki-NLP/opus-mt-en-fr` | Multi-language notes |
129
-
130
- ---
131
-
132
- ## ✏️ Challenge
133
-
134
- In `app.py`, find the **EXPERIMENT ZONE** at the bottom.
135
-
136
- Uncomment the `/summarize` endpoint, and try summarizing a long clinical note. Check `/docs` — it appears immediately!
137
-
138
- ---
139
-
140
- ➡️ **Next: [Step 3 — Background Tasks →](../step_03_live_model/README.md)**
141
-
142
- *(For when your model takes too long to run synchronously)*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_02_medical_api/app.py DELETED
@@ -1,256 +0,0 @@
1
- """
2
- Step 2 — Real Medical NLP API
3
- ==============================
4
- We load a Hugging Face model ONCE at startup, then reuse it for every request.
5
- This answers the question: "Does the model run live, or use pre-existing results?"
6
-
7
- Answer: IT RUNS LIVE — but the model is loaded into memory only once.
8
- Each request calls the already-loaded model. Very fast after the first load!
9
-
10
- Model used: d4data/biomedical-ner-all
11
- A Named Entity Recognition model trained on biomedical text.
12
- It finds: Disease, Drug, Chemical, Gene, Protein mentions in text.
13
-
14
- Run it:
15
- cd step_02_medical_api
16
- uvicorn app:app --reload --port 8000
17
-
18
- First request is slow (model downloads ~500MB on first run).
19
- Every request after that is fast.
20
- """
21
-
22
- from fastapi import FastAPI, HTTPException
23
- from pydantic import BaseModel
24
- from typing import Optional
25
- import time
26
- import os
27
-
28
- # ── Load the model ONCE at startup ────────────────────────────────────────────
29
- # This is the key architectural decision:
30
- # ✅ Load once → serve thousands of requests without reloading
31
- # ❌ Load per request → 30 second wait on every single call (unusable!)
32
-
33
- print("⏳ Loading biomedical NLP model... (first time downloads ~500MB)")
34
- start = time.time()
35
-
36
- try:
37
- from transformers import pipeline
38
-
39
- # Named Entity Recognition model fine-tuned on biomedical text
40
- # Finds: Disease, Drug, Chemical, Gene, Species, etc.
41
- ner_pipeline = pipeline(
42
- "ner",
43
- model="d4data/biomedical-ner-all",
44
- aggregation_strategy="simple", # Merges tokens into full words
45
- )
46
-
47
- # Also load a zero-shot classifier for urgency detection
48
- # This model can classify text into ANY labels you define — no fine-tuning!
49
- classifier = pipeline(
50
- "zero-shot-classification",
51
- model="facebook/bart-large-mnli",
52
- )
53
-
54
- MODEL_LOADED = True
55
- print(f"✅ Models loaded in {time.time() - start:.1f}s")
56
-
57
- except Exception as e:
58
- print(f"⚠️ Could not load model: {e}")
59
- print("Running in DEMO MODE with fake results.")
60
- MODEL_LOADED = False
61
-
62
-
63
- # ── App definition ─────────────────────────────────────────────────────────────
64
- app = FastAPI(
65
- title="Medical NLP API",
66
- description="""
67
- A real-time NLP API for clinical text analysis.
68
-
69
- Powered by Hugging Face transformer models:
70
- - **NER**: Extracts diseases, drugs, genes from clinical notes
71
- - **Urgency Classification**: Triage helper using zero-shot classification
72
-
73
- The model loads once at startup and runs live on each request.
74
- """,
75
- version="2.0.0",
76
- )
77
-
78
-
79
- # ── Request / Response models ─────────────────────────────────────────────────
80
- class ClinicalNote(BaseModel):
81
- text: str
82
- patient_id: Optional[str] = None
83
-
84
- model_config = {
85
- "json_schema_extra": {
86
- "examples": [
87
- {
88
- "text": "Patient presents with acute myocardial infarction. "
89
- "Currently on aspirin 100mg and metoprolol. "
90
- "History of BRCA1 mutation.",
91
- "patient_id": "P001"
92
- }
93
- ]
94
- }
95
- }
96
-
97
-
98
- class EntityResult(BaseModel):
99
- entity_type: str
100
- text: str
101
- confidence: float
102
-
103
-
104
- class NERResponse(BaseModel):
105
- patient_id: Optional[str]
106
- entities: list[EntityResult]
107
- entity_summary: dict
108
- processing_time_ms: float
109
- model_used: str
110
-
111
-
112
- class UrgencyResponse(BaseModel):
113
- text: str
114
- urgency_level: str
115
- confidence: float
116
- all_scores: dict
117
-
118
-
119
- # ── Endpoints ─────────────────────────────────────────────────────────────────
120
- @app.get("/")
121
- def root():
122
- return {
123
- "service": "Medical NLP API",
124
- "model_loaded": MODEL_LOADED,
125
- "endpoints": ["/extract-entities", "/classify-urgency", "/analyze-full"],
126
- "docs": "/docs",
127
- }
128
-
129
-
130
- @app.get("/health")
131
- def health():
132
- """Health check — useful for deployment monitoring"""
133
- return {"status": "healthy", "model_loaded": MODEL_LOADED}
134
-
135
-
136
- @app.post("/extract-entities", response_model=NERResponse)
137
- def extract_entities(note: ClinicalNote):
138
- """
139
- Extract biomedical named entities from clinical text.
140
-
141
- Finds: Disease, Drug, Chemical, Gene, Protein, Species mentions.
142
- Uses Hugging Face NER model running live on each request.
143
- """
144
- t0 = time.time()
145
-
146
- if MODEL_LOADED:
147
- try:
148
- raw_entities = ner_pipeline(note.text)
149
- except Exception as e:
150
- raise HTTPException(status_code=500, detail=f"Model error: {str(e)}")
151
- else:
152
- # Demo mode — return fake entities so you can test the API structure
153
- raw_entities = [
154
- {"entity_group": "Disease", "word": "myocardial infarction", "score": 0.98},
155
- {"entity_group": "Chemical", "word": "aspirin", "score": 0.95},
156
- {"entity_group": "Gene", "word": "BRCA1", "score": 0.92},
157
- ]
158
-
159
- # Clean and structure the results
160
- entities = [
161
- EntityResult(
162
- entity_type=e.get("entity_group", e.get("entity", "UNKNOWN")),
163
- text=e["word"],
164
- confidence=round(float(e["score"]), 3),
165
- )
166
- for e in raw_entities
167
- if float(e["score"]) > 0.7 # Filter low-confidence results
168
- ]
169
-
170
- # Summarize by type
171
- summary = {}
172
- for ent in entities:
173
- summary.setdefault(ent.entity_type, []).append(ent.text)
174
-
175
- return NERResponse(
176
- patient_id=note.patient_id,
177
- entities=entities,
178
- entity_summary=summary,
179
- processing_time_ms=round((time.time() - t0) * 1000, 1),
180
- model_used="d4data/biomedical-ner-all" if MODEL_LOADED else "demo-mode",
181
- )
182
-
183
-
184
- @app.post("/classify-urgency", response_model=UrgencyResponse)
185
- def classify_urgency(note: ClinicalNote):
186
- """
187
- Classify the urgency level of a clinical note.
188
-
189
- Uses ZERO-SHOT classification — no medical training data needed!
190
- The model reasons about urgency from general language understanding.
191
- Great for rapid prototyping before you have labeled data.
192
- """
193
- urgency_labels = [
194
- "life-threatening emergency",
195
- "urgent - needs attention within hours",
196
- "routine - can wait for next appointment",
197
- "administrative - no clinical urgency",
198
- ]
199
-
200
- if MODEL_LOADED:
201
- try:
202
- result = classifier(note.text, candidate_labels=urgency_labels)
203
- except Exception as e:
204
- raise HTTPException(status_code=500, detail=f"Model error: {str(e)}")
205
- else:
206
- # Demo mode
207
- result = {
208
- "labels": urgency_labels,
209
- "scores": [0.65, 0.25, 0.08, 0.02],
210
- "sequence": note.text,
211
- }
212
-
213
- scores_dict = dict(zip(result["labels"], [round(s, 3) for s in result["scores"]]))
214
-
215
- return UrgencyResponse(
216
- text=note.text,
217
- urgency_level=result["labels"][0],
218
- confidence=round(result["scores"][0], 3),
219
- all_scores=scores_dict,
220
- )
221
-
222
-
223
- @app.post("/analyze-full")
224
- def analyze_full(note: ClinicalNote):
225
- """
226
- Combined endpoint: runs both NER and urgency classification in one call.
227
- This is the 'production' endpoint a clinician dashboard would call.
228
- """
229
- entities_result = extract_entities(note)
230
- urgency_result = classify_urgency(note)
231
-
232
- return {
233
- "patient_id": note.patient_id,
234
- "entities": entities_result.entity_summary,
235
- "urgency": {
236
- "level": urgency_result.urgency_level,
237
- "confidence": urgency_result.confidence,
238
- },
239
- "raw_text_length": len(note.text),
240
- "total_entities_found": len(entities_result.entities),
241
- }
242
-
243
-
244
- # ── EXPERIMENT ZONE ────────────────────────────────────────────────────────────
245
- # Try adding a new endpoint! Ideas:
246
- #
247
- # @app.post("/summarize")
248
- # def summarize_note(note: ClinicalNote):
249
- # summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
250
- # result = summarizer(note.text, max_length=60, min_length=20)
251
- # return {"summary": result[0]["summary_text"]}
252
- #
253
- # @app.post("/translate-to-patient")
254
- # def patient_friendly(note: ClinicalNote):
255
- # """Convert clinical jargon to plain language using a text2text model"""
256
- # pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_03_live_model/README.md DELETED
@@ -1,132 +0,0 @@
1
- # ⚡ Step 3 — Background Tasks: When Models Take Too Long
2
-
3
- > ⏱ **Time: ~10 minutes** | The pattern for heavy models
4
-
5
- ---
6
-
7
- ## The Problem
8
-
9
- Your whole-slide pathology model takes **15 seconds**. Your batch processing job takes **2 minutes**.
10
-
11
- You **cannot** make the caller wait — HTTP requests time out, users get frustrated, mobile apps crash.
12
-
13
- ## The Solution: The Job Queue Pattern
14
-
15
- ```
16
- Instead of: Send request → wait 15s → get result
17
- Do this: Send request → get job_id immediately (< 1s)
18
- Poll every 2s → "still running..."
19
- Eventually → "complete! here are your results"
20
- ```
21
-
22
- ---
23
-
24
- ## ▶️ Start the Server
25
-
26
- ```bash
27
- cd step_03_live_model
28
- uvicorn app:app --reload --port 8000
29
- ```
30
-
31
- ---
32
-
33
- ## 🧪 Walk Through the Full Flow
34
-
35
- ### Step 1: Submit a job (returns INSTANTLY)
36
- ```bash
37
- curl -X POST http://localhost:8000/jobs/analyze \
38
- -H "Content-Type: application/json" \
39
- -d '{"text": "Pathology slide: adenocarcinoma tissue", "model_type": "slide_analysis"}'
40
- ```
41
-
42
- Response (instant!):
43
- ```json
44
- {
45
- "job_id": "a3f2c1d9",
46
- "status": "pending",
47
- "message": "Job submitted. Poll GET /jobs/a3f2c1d9 to check status.",
48
- "expected_wait_s": 15
49
- }
50
- ```
51
-
52
- ### Step 2: Poll for status
53
- ```bash
54
- curl http://localhost:8000/jobs/a3f2c1d9
55
- ```
56
-
57
- ```json
58
- {"status": "running", ...}
59
- ```
60
-
61
- ### Step 3: Get results when done
62
- ```bash
63
- curl http://localhost:8000/jobs/a3f2c1d9/result
64
- ```
65
-
66
- ```json
67
- {
68
- "result": {
69
- "tissue_type": "adenocarcinoma",
70
- "grade": "grade_2",
71
- "tumor_percentage": 0.35,
72
- "confidence": 0.91
73
- }
74
- }
75
- ```
76
-
77
- ---
78
-
79
- ## 🏗️ Try All Three Model Types
80
-
81
- In `/docs`, submit jobs with different `model_type` values:
82
-
83
- | Model Type | Simulated Wait | Use Case |
84
- |-----------|---------------|----------|
85
- | `quick_ner` | 2 seconds | Fast NER on short notes |
86
- | `full_analysis` | 8 seconds | NER + classification + summary |
87
- | `slide_analysis` | 15 seconds | Pathology slide (heavy model) |
88
-
89
- Submit multiple jobs at once — the server handles them all simultaneously!
90
-
91
- ---
92
-
93
- ## 💡 How It Works in the Code
94
-
95
- ```python
96
- @app.post("/jobs/analyze", status_code=202)
97
- def submit_analysis(request, background_tasks: BackgroundTasks):
98
- job_id = create_job_record()
99
-
100
- # Magic line — this returns immediately, model runs separately
101
- background_tasks.add_task(run_slow_model, job_id, request.text)
102
-
103
- return {"job_id": job_id, "status": "pending"} # ← Returns NOW
104
- ```
105
-
106
- `BackgroundTasks` is built into FastAPI — no extra dependencies needed.
107
-
108
- **202 status code** means "Accepted" — the server says "I got your request and will process it."
109
-
110
- ---
111
-
112
- ## 🔄 Production Upgrade Path
113
-
114
- The in-memory job store (`jobs: dict = {}`) works for learning but has limits:
115
- - Restarts wipe all jobs
116
- - Doesn't work across multiple server instances
117
-
118
- For production, replace with:
119
- ```python
120
- # Drop-in replacement: Redis job store
121
- import redis
122
- r = redis.Redis()
123
- r.set(f"job:{job_id}", json.dumps(job_data))
124
- ```
125
-
126
- Or use [Celery](https://docs.celeryq.dev/) for full job queue management.
127
-
128
- ---
129
-
130
- ➡️ **Next: [Step 4 — Deploy to Render →](../step_04_deploy_render/README.md)**
131
-
132
- *(Put your API on the internet for free)*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_03_live_model/app.py DELETED
@@ -1,240 +0,0 @@
1
- """
2
- Step 3 — Background Tasks & Job Queue
3
- ======================================
4
- What if your model takes 30 seconds? Or 10 minutes? (Think: whole-slide imaging)
5
-
6
- You can't make the caller wait. Instead:
7
- 1. Accept the job, return a job_id immediately
8
- 2. Run the model in the background
9
- 3. Caller polls: "is job 42 done yet?"
10
- 4. When done, return results
11
-
12
- This is the standard pattern for:
13
- - Large image analysis (pathology slides)
14
- - Batch processing of hundreds of notes
15
- - Any model that takes > 3-5 seconds
16
-
17
- Run it:
18
- cd step_03_live_model
19
- uvicorn app:app --reload --port 8000
20
- """
21
-
22
- from fastapi import FastAPI, BackgroundTasks, HTTPException
23
- from pydantic import BaseModel
24
- from typing import Optional, Literal
25
- from datetime import datetime
26
- import asyncio
27
- import uuid
28
- import time
29
-
30
- app = FastAPI(
31
- title="Async Medical Analysis API",
32
- description="""
33
- Demonstrates the background job pattern for long-running ML models.
34
-
35
- Pattern:
36
- 1. POST /jobs/analyze → returns job_id immediately
37
- 2. GET /jobs/{job_id} → check status (pending/running/complete/failed)
38
- 3. GET /jobs/{job_id}/result → get the actual results
39
- """,
40
- version="3.0.0",
41
- )
42
-
43
-
44
- # ── In-memory job store ────────────────────────────────────────────────────────
45
- # In production, replace this with Redis or a database!
46
- jobs: dict = {}
47
-
48
-
49
- class Job(BaseModel):
50
- job_id: str
51
- status: Literal["pending", "running", "complete", "failed"]
52
- created_at: str
53
- completed_at: Optional[str] = None
54
- result: Optional[dict] = None
55
- error: Optional[str] = None
56
-
57
-
58
- # ── Simulated ML models ────────────────────────────────────────────────────────
59
- async def run_slow_model(job_id: str, text: str, model_type: str):
60
- """
61
- Simulates a slow model (like whole-slide image analysis).
62
-
63
- In reality, replace `await asyncio.sleep()` with your actual model call.
64
- The key: run it in the background so the API stays responsive.
65
- """
66
- jobs[job_id]["status"] = "running"
67
-
68
- try:
69
- # Simulate different processing times for different models
70
- processing_times = {
71
- "quick_ner": 2, # Fast: NER on short text
72
- "full_analysis": 8, # Medium: NER + classification + summary
73
- "slide_analysis": 15, # Slow: Pathology slide (simulated)
74
- }
75
- wait_time = processing_times.get(model_type, 5)
76
-
77
- # Simulate model running...
78
- await asyncio.sleep(wait_time)
79
-
80
- # Fake results based on model type
81
- if model_type == "quick_ner":
82
- result = {
83
- "entities": ["diabetes", "metformin", "HbA1c"],
84
- "processing_time_s": wait_time,
85
- }
86
- elif model_type == "full_analysis":
87
- result = {
88
- "entities": ["stage III colorectal cancer", "FOLFOX", "KRAS"],
89
- "urgency": "urgent",
90
- "summary": "Oncology patient requiring chemotherapy initiation.",
91
- "recommended_specialists": ["oncology", "surgery"],
92
- "processing_time_s": wait_time,
93
- }
94
- elif model_type == "slide_analysis":
95
- result = {
96
- "tissue_type": "adenocarcinoma",
97
- "grade": "grade_2",
98
- "mitotic_index": 12,
99
- "tumor_percentage": 0.35,
100
- "confidence": 0.91,
101
- "regions_analyzed": 1247,
102
- "processing_time_s": wait_time,
103
- }
104
- else:
105
- result = {"status": "unknown model type"}
106
-
107
- jobs[job_id]["status"] = "complete"
108
- jobs[job_id]["result"] = result
109
- jobs[job_id]["completed_at"] = datetime.now().isoformat()
110
-
111
- except Exception as e:
112
- jobs[job_id]["status"] = "failed"
113
- jobs[job_id]["error"] = str(e)
114
-
115
-
116
- # ── Request models ─────────────────────────────────────────────────────────────
117
- class AnalysisRequest(BaseModel):
118
- text: str
119
- model_type: Literal["quick_ner", "full_analysis", "slide_analysis"] = "quick_ner"
120
- patient_id: Optional[str] = None
121
-
122
- model_config = {
123
- "json_schema_extra": {
124
- "examples": [
125
- {
126
- "text": "Patient with stage III colorectal cancer, KRAS wild-type",
127
- "model_type": "full_analysis",
128
- "patient_id": "P001"
129
- }
130
- ]
131
- }
132
- }
133
-
134
-
135
- # ── Endpoints ─────────────────────────────────────────────────────────────────
136
- @app.get("/")
137
- def root():
138
- return {
139
- "service": "Async Medical Analysis API",
140
- "pattern": "Submit job → poll status → retrieve results",
141
- "active_jobs": len(jobs),
142
- }
143
-
144
-
145
- @app.post("/jobs/analyze", status_code=202)
146
- def submit_analysis(request: AnalysisRequest, background_tasks: BackgroundTasks):
147
- """
148
- Submit an analysis job. Returns IMMEDIATELY with a job_id.
149
- Status 202 = "Accepted" (not done yet, but will be)
150
-
151
- The model runs in the background.
152
- Poll /jobs/{job_id} to check progress.
153
- """
154
- job_id = str(uuid.uuid4())[:8] # Short readable ID
155
-
156
- # Create the job record
157
- jobs[job_id] = {
158
- "job_id": job_id,
159
- "status": "pending",
160
- "created_at": datetime.now().isoformat(),
161
- "patient_id": request.patient_id,
162
- "model_type": request.model_type,
163
- "completed_at": None,
164
- "result": None,
165
- "error": None,
166
- }
167
-
168
- # This returns immediately — model runs in background
169
- background_tasks.add_task(run_slow_model, job_id, request.text, request.model_type)
170
-
171
- return {
172
- "job_id": job_id,
173
- "status": "pending",
174
- "message": f"Job submitted. Poll GET /jobs/{job_id} to check status.",
175
- "expected_wait_s": {"quick_ner": 2, "full_analysis": 8, "slide_analysis": 15}
176
- .get(request.model_type, 5),
177
- }
178
-
179
-
180
- @app.get("/jobs/{job_id}")
181
- def get_job_status(job_id: str):
182
- """
183
- Check the status of a submitted job.
184
- Status will be: pending → running → complete (or failed)
185
- """
186
- if job_id not in jobs:
187
- raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
188
- return jobs[job_id]
189
-
190
-
191
- @app.get("/jobs/{job_id}/result")
192
- def get_job_result(job_id: str):
193
- """
194
- Get results once job is complete.
195
- Returns 400 if job is still running.
196
- """
197
- if job_id not in jobs:
198
- raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
199
-
200
- job = jobs[job_id]
201
-
202
- if job["status"] == "pending":
203
- return {"message": "Job is queued, not started yet", "status": "pending"}
204
- elif job["status"] == "running":
205
- return {"message": "Model is currently running...", "status": "running"}
206
- elif job["status"] == "failed":
207
- raise HTTPException(status_code=500, detail=job.get("error", "Unknown error"))
208
- else:
209
- return {
210
- "job_id": job_id,
211
- "status": "complete",
212
- "result": job["result"],
213
- "completed_at": job["completed_at"],
214
- }
215
-
216
-
217
- @app.get("/jobs")
218
- def list_jobs():
219
- """List all jobs and their statuses"""
220
- return {
221
- "total": len(jobs),
222
- "jobs": [
223
- {
224
- "job_id": jid,
225
- "status": j["status"],
226
- "model_type": j.get("model_type"),
227
- "created_at": j["created_at"],
228
- }
229
- for jid, j in jobs.items()
230
- ],
231
- }
232
-
233
-
234
- @app.delete("/jobs/{job_id}")
235
- def delete_job(job_id: str):
236
- """Clean up a completed job"""
237
- if job_id not in jobs:
238
- raise HTTPException(status_code=404, detail="Job not found")
239
- del jobs[job_id]
240
- return {"message": f"Job {job_id} deleted"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_04_deploy_render/README.md DELETED
@@ -1,136 +0,0 @@
1
- # 🌐 Step 4 — Deploy to Render (Free!)
2
-
3
- > ⏱ **Time: ~10 minutes** | Your API on the public internet
4
-
5
- ---
6
-
7
- ## What You'll Do
8
-
9
- Take your local API and deploy it to a public URL so:
10
- - Collaborators can call it from anywhere
11
- - You can demo it from a browser
12
- - A frontend app (React, Streamlit) can call it
13
-
14
- **Cost: Free** on Render's free tier (512MB RAM, sleeps after 15 min inactivity).
15
-
16
- ---
17
-
18
- ## 📋 Prerequisites
19
-
20
- - [ ] A [GitHub account](https://github.com) (free)
21
- - [ ] A [Render account](https://render.com) — sign up with GitHub (free)
22
- - [ ] This tutorial repo pushed to your GitHub
23
-
24
- ---
25
-
26
- ## 🚀 Deployment Steps
27
-
28
- ### 1. Push to GitHub
29
-
30
- ```bash
31
- # In your Codespace terminal:
32
- git add .
33
- git commit -m "Add medical NLP API tutorial"
34
- git push origin main
35
- ```
36
-
37
- ### 2. Connect to Render
38
-
39
- 1. Go to [render.com](https://render.com) → **New** → **Web Service**
40
- 2. Click **"Connect a repository"** → Select your GitHub repo
41
- 3. Fill in settings:
42
-
43
- | Setting | Value |
44
- |---------|-------|
45
- | **Name** | `medical-nlp-api` (or any name) |
46
- | **Runtime** | Python 3 |
47
- | **Build Command** | `pip install -r requirements.txt` |
48
- | **Start Command** | `uvicorn step_04_deploy_render.app:app --host 0.0.0.0 --port $PORT` |
49
- | **Instance Type** | Free |
50
-
51
- 4. Click **"Create Web Service"**
52
-
53
- ### 3. Wait ~3 minutes
54
-
55
- Render builds your container, installs packages, and starts the server.
56
- You'll see build logs in real-time.
57
-
58
- ### 4. Your API is live! 🎉
59
-
60
- Visit `https://your-app-name.onrender.com/docs` — your Swagger UI is public!
61
-
62
- ---
63
-
64
- ## ⚠️ Free Tier Gotchas
65
-
66
- | Issue | What it means | Solution |
67
- |-------|--------------|----------|
68
- | **Sleeps after 15 min** | First request takes ~30s to "wake up" | Expected behavior on free tier |
69
- | **512MB RAM limit** | Large models (GPT-2, BERT-large) may crash | Use smaller models for free tier |
70
- | **Model re-downloads on restart** | HuggingFace cache resets | Set `HF_HOME=/tmp/huggingface` in env vars |
71
-
72
- ---
73
-
74
- ## 🧪 Test Your Live API
75
-
76
- ```bash
77
- # Replace with your actual Render URL
78
- curl https://your-app.onrender.com/health
79
-
80
- curl -X POST https://your-app.onrender.com/extract \
81
- -H "Content-Type: application/json" \
82
- -d '{"text": "Patient has hypertension and diabetes", "patient_id": "test-001"}'
83
- ```
84
-
85
- ---
86
-
87
- ## 📡 Calling Your API from Python (for collaborators)
88
-
89
- Share this snippet with colleagues who want to use your model:
90
-
91
- ```python
92
- import httpx
93
-
94
- API_URL = "https://your-app.onrender.com" # Replace with your URL
95
-
96
- def extract_medical_entities(clinical_note: str) -> dict:
97
- """Call the medical NLP API — no Python ML libraries needed!"""
98
- response = httpx.post(
99
- f"{API_URL}/extract",
100
- json={"text": clinical_note, "patient_id": "research-001"}
101
- )
102
- response.raise_for_status()
103
- return response.json()
104
-
105
- # Usage
106
- note = "Patient with stage 2 breast cancer, BRCA1 positive, starting tamoxifen."
107
- results = extract_medical_entities(note)
108
- print(results["summary"])
109
- # {'Disease': ['breast cancer'], 'Gene': ['BRCA1'], 'Chemical': ['tamoxifen']}
110
- ```
111
-
112
- Your colleagues don't need FastAPI, transformers, or PyTorch installed — just `httpx`!
113
-
114
- ---
115
-
116
- ## 🌟 What You've Achieved
117
-
118
- You've completed the full API lifecycle:
119
- 1. ✅ **Designed** — understood what the API should do
120
- 2. ✅ **Built** — FastAPI with Hugging Face models
121
- 3. ✅ **Tested** — Swagger UI, curl, Python client
122
- 4. ✅ **Documented** — auto-generated OpenAPI spec
123
- 5. ✅ **Deployed** — live on the public internet
124
-
125
- ---
126
-
127
- ## 📖 Resources
128
-
129
- - [FastAPI Tutorial in VS Code](https://code.visualstudio.com/docs/python/tutorial-fastapi)
130
- - [Deploying ML Models with FastAPI](https://www.analyticsvidhya.com/blog/2022/09/deploying-ml-models-using-fastapi/)
131
- - [Hugging Face Model Hub](https://huggingface.co/models)
132
- - [Render Documentation](https://render.com/docs)
133
-
134
- ---
135
-
136
- ➡️ **[Go back to the main README](../README.md)** to see the full picture and next steps
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_04_deploy_render/app.py DELETED
@@ -1,214 +0,0 @@
1
- """
2
- Step 4 — Production-Ready API for Render Deployment
3
- =====================================================
4
- This is a 'production-lite' version of the medical API:
5
- - Lightweight model choice (fast to load on free hosting)
6
- - Rate limiting (prevent abuse)
7
- - CORS headers (allows a browser frontend to call it)
8
- - Proper error handling
9
- - /health endpoint for Render's health checks
10
-
11
- Deploy steps:
12
- 1. Push this repo to GitHub
13
- 2. Go to render.com → New → Web Service
14
- 3. Connect your repo, set:
15
- Build Command: pip install -r requirements.txt
16
- Start Command: uvicorn step_04_deploy_render.app:app --host 0.0.0.0 --port $PORT
17
- 4. Done! Your API is live at https://your-app.onrender.com
18
-
19
- Run locally:
20
- cd step_04_deploy_render
21
- uvicorn app:app --host 0.0.0.0 --port 8000
22
- """
23
-
24
- import os
25
- import time
26
- from datetime import datetime
27
- from typing import Optional
28
- from contextlib import asynccontextmanager
29
-
30
- from fastapi import FastAPI, HTTPException, Request
31
- from fastapi.middleware.cors import CORSMiddleware
32
- from pydantic import BaseModel
33
-
34
- # ── Rate limiting (optional but good practice) ─────────────────────────────────
35
- try:
36
- from slowapi import Limiter, _rate_limit_exceeded_handler
37
- from slowapi.util import get_remote_address
38
- from slowapi.errors import RateLimitExceeded
39
- limiter = Limiter(key_func=get_remote_address)
40
- RATE_LIMIT_ENABLED = True
41
- except ImportError:
42
- RATE_LIMIT_ENABLED = False
43
-
44
-
45
- # ── Model loading with lifespan (modern FastAPI pattern) ───────────────────────
46
- ml_models = {}
47
-
48
-
49
- @asynccontextmanager
50
- async def lifespan(app: FastAPI):
51
- """
52
- Modern way to run startup/shutdown code in FastAPI.
53
- Model loads ONCE when server starts. Cleanup on shutdown.
54
- """
55
- print("🚀 Server starting — loading models...")
56
- start = time.time()
57
-
58
- try:
59
- from transformers import pipeline
60
-
61
- # Use a lightweight model for free hosting (loads faster, uses less RAM)
62
- # Great for Render's free tier (512MB RAM limit)
63
- ml_models["ner"] = pipeline(
64
- "ner",
65
- model="d4data/biomedical-ner-all",
66
- aggregation_strategy="simple",
67
- )
68
- print(f"✅ Model loaded in {time.time() - start:.1f}s")
69
- ml_models["ready"] = True
70
-
71
- except Exception as e:
72
- print(f"⚠️ Model load failed: {e}. Running in demo mode.")
73
- ml_models["ready"] = False
74
-
75
- yield # Server is running here
76
-
77
- # Cleanup (runs on shutdown)
78
- ml_models.clear()
79
- print("🛑 Server shutting down — models cleared")
80
-
81
-
82
- # ── App setup ─────────────────────────────────────────────────────────────────
83
- app = FastAPI(
84
- title="Medical NLP API — Production",
85
- description="""
86
- Production-ready Medical NLP API.
87
-
88
- Live demo: [your-app.onrender.com/docs](https://your-app.onrender.com/docs)
89
-
90
- Built with FastAPI + Hugging Face Transformers.
91
- Deployed on Render.
92
- """,
93
- version="4.0.0",
94
- lifespan=lifespan,
95
- )
96
-
97
- # Add rate limiter
98
- if RATE_LIMIT_ENABLED:
99
- app.state.limiter = limiter
100
- app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
101
-
102
- # ── CORS — allow browsers and frontend apps to call this API ──────────────────
103
- app.add_middleware(
104
- CORSMiddleware,
105
- allow_origins=["*"], # In production: replace with your frontend URL
106
- allow_credentials=True,
107
- allow_methods=["*"],
108
- allow_headers=["*"],
109
- )
110
-
111
-
112
- # ── Request models ─────────────────────────────────────────────────────────────
113
- class NoteRequest(BaseModel):
114
- text: str
115
- patient_id: Optional[str] = None
116
-
117
- model_config = {
118
- "json_schema_extra": {
119
- "examples": [
120
- {
121
- "text": "Patient has type 2 diabetes, started on metformin 500mg. HbA1c 8.2%.",
122
- "patient_id": "demo-001",
123
- }
124
- ]
125
- }
126
- }
127
-
128
-
129
- # ── Endpoints ─────────────────────────────────────────────────────────────────
130
- @app.get("/")
131
- def root():
132
- """Root endpoint — shows API info"""
133
- return {
134
- "service": "Medical NLP API",
135
- "version": "4.0.0",
136
- "model_ready": ml_models.get("ready", False),
137
- "docs": "/docs",
138
- "health": "/health",
139
- }
140
-
141
-
142
- @app.get("/health")
143
- def health():
144
- """
145
- Health check endpoint.
146
- Render uses this to know if your service is up.
147
- Always return 200 if server is running.
148
- """
149
- return {
150
- "status": "healthy",
151
- "model_loaded": ml_models.get("ready", False),
152
- "timestamp": datetime.now().isoformat(),
153
- }
154
-
155
-
156
- @app.post("/extract")
157
- def extract_entities(request: NoteRequest, req: Request = None):
158
- """
159
- Extract biomedical entities from clinical text.
160
- Rate limited to 30 requests/minute per IP.
161
- """
162
- t0 = time.time()
163
-
164
- if ml_models.get("ready"):
165
- try:
166
- raw = ml_models["ner"](request.text)
167
- entities = [
168
- {"type": e.get("entity_group", e.get("entity")), "text": e["word"], "score": round(float(e["score"]), 3)}
169
- for e in raw if float(e["score"]) > 0.75
170
- ]
171
- except Exception as e:
172
- raise HTTPException(status_code=500, detail=str(e))
173
- else:
174
- # Demo mode
175
- entities = [
176
- {"type": "Disease", "text": "diabetes", "score": 0.97},
177
- {"type": "Chemical", "text": "metformin", "score": 0.95},
178
- ]
179
-
180
- summary = {}
181
- for e in entities:
182
- summary.setdefault(e["type"], []).append(e["text"])
183
-
184
- return {
185
- "patient_id": request.patient_id,
186
- "entities": entities,
187
- "summary": summary,
188
- "entity_count": len(entities),
189
- "processing_ms": round((time.time() - t0) * 1000, 1),
190
- }
191
-
192
-
193
- @app.get("/demo")
194
- def demo():
195
- """
196
- Pre-run example — shows what the API returns without sending your own data.
197
- Safe to call from any browser or tool.
198
- """
199
- return {
200
- "example_input": "Patient has type 2 diabetes and hypertension. Prescribed metformin 1000mg and lisinopril 10mg.",
201
- "example_output": {
202
- "entities": [
203
- {"type": "Disease", "text": "type 2 diabetes", "score": 0.98},
204
- {"type": "Disease", "text": "hypertension", "score": 0.96},
205
- {"type": "Chemical", "text": "metformin", "score": 0.97},
206
- {"type": "Chemical", "text": "lisinopril", "score": 0.95},
207
- ],
208
- "summary": {
209
- "Disease": ["type 2 diabetes", "hypertension"],
210
- "Chemical": ["metformin", "lisinopril"],
211
- },
212
- },
213
- "note": "POST /extract with your own text to run the live model",
214
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
step_04_deploy_render/render.yaml DELETED
@@ -1,18 +0,0 @@
1
- services:
2
- - type: web
3
- name: medical-nlp-api
4
- runtime: python
5
- buildCommand: "pip install -r requirements.txt"
6
- startCommand: "uvicorn step_04_deploy_render.app:app --host 0.0.0.0 --port $PORT"
7
-
8
- # Free tier settings
9
- plan: free
10
-
11
- envVars:
12
- - key: PYTHON_VERSION
13
- value: 3.11.0
14
- - key: HF_HOME
15
- value: /tmp/huggingface # Cache models in /tmp (persists between requests)
16
-
17
- # Health check — Render pings this to know if your app is up
18
- healthCheckPath: /health