A small full-stack demo that predicts house prices from size, bedroom count, and distance from the city center, using a scikit-learn linear regression model served through a FastAPI backend and a plain HTML/JS frontend.
- FastAPI backend with a single
/predictendpoint - Linear regression model (
scikit-learn) trained on a small sample housing dataset - Static frontend (HTML + vanilla JS) served directly by FastAPI
- Basic test coverage with
pytest/ FastAPI'sTestClient - CORS enabled for all origins (useful for local development)
.
├── main.py # FastAPI app: serves the frontend and the /predict endpoint
├── train_model.py # Trains the linear regression model and saves model.pkl
├── test_model.py # Tests for the model and the API
├── model.pkl # Trained model (generated by train_model.py)
├── index.html # Frontend UI
└── static/
└── index.css # Frontend styling
- Python 3.9+
fastapiuvicornscikit-learnjoblibpydanticpytest(for running tests)
Install dependencies:
pip install fastapi uvicorn scikit-learn joblib pytest-
Train the model (generates
model.pkl):python train_model.py
-
Run the API server:
uvicorn main:app --reload
-
Open the app in your browser:
http://localhost:8000
Predicts a house price given size, bedrooms, and distance from the city.
Request body:
{
"size": 100,
"bedrooms": 3,
"distance": 5
}Response:
{
"prediction": 320000.0
}Serves the frontend (index.html).
Run the test suite with:
pytestTests cover:
- That the model produces a positive price prediction for valid input
- That the API returns a
422 Unprocessable Entityfor invalid input
The model is a LinearRegression from scikit-learn, trained on a small hardcoded dataset of six houses with three features:
| Feature | Description |
|---|---|
size |
Property size in m² |
bedrooms |
Number of bedrooms |
distance |
Distance from city center (km) |
This is a toy dataset for demonstration purposes only — with just six training examples, the model is not suitable for real-world price predictions. Replace X and y in train_model.py with a larger, real dataset before using this for anything meaningful.
- CORS is wide open (
allow_origins=["*"]) — restrict this before deploying anywhere public - No input validation beyond basic type checking (e.g. negative sizes/bedrooms are accepted)
- Training dataset is tiny and hardcoded — consider loading from a CSV or database
- No persistence/versioning of trained models beyond overwriting
model.pkl
MIT