that # Real-Time Purchase Prediction API - Usage Guide
This FastAPI application provides real-time purchase prediction for e-commerce sessions. The API accepts preprocessed feature vectors and returns predictions with confidence scores.
python -m uvicorn src.app:app --reload --host 0.0.0.0 --port 8000python src/app.pyThe server will start on http://localhost:8000
GET /
Returns basic API information.
Response:
{
"message": "Real-Time Purchase Prediction API",
"docs": "/docs",
"health": "/health"
}GET /health
Check if the API and model are loaded and ready.
Response:
{
"status": "healthy",
"model_loaded": true,
"api_version": "1.0.0"
}POST /predict
Make a single purchase prediction.
Request Body:
{
"features": {
"0": 0.123,
"1": 0.456,
"2": 0.789,
...
"65": 0.234
}
}Response:
{
"prediction": 1,
"prediction_label": "Purchase",
"probability_no_purchase": 0.2341,
"probability_purchase": 0.7659,
"confidence": 0.7659
}Fields:
prediction: Integer (0 = No Purchase, 1 = Purchase)prediction_label: Human-readable label ("No Purchase" or "Purchase")probability_no_purchase: Probability of no purchase (0-1)probability_purchase: Probability of purchase (0-1)confidence: Maximum probability (confidence score 0-1)
POST /predict/batch
Make predictions for multiple samples at once.
Request Body:
[
{
"features": {
"0": 0.123,
"1": 0.456,
...
"65": 0.234
}
},
{
"features": {
"0": 0.987,
"1": 0.654,
...
"65": 0.321
}
}
]Response:
[
{
"prediction": 1,
"prediction_label": "Purchase",
"probability_no_purchase": 0.2341,
"probability_purchase": 0.7659,
"confidence": 0.7659
},
{
"prediction": 0,
"prediction_label": "No Purchase",
"probability_no_purchase": 0.8123,
"probability_purchase": 0.1877,
"confidence": 0.8123
}
]The easiest way to test the API is with the provided demo script:
# Terminal 1: Start the API server
python -m uvicorn src.app:app --reload
# Terminal 2: Run the test script
python demo_api.pyHealth Check:
curl http://localhost:8000/healthSingle Prediction:
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d @sample_prediction_request.jsonimport requests
import pandas as pd
# Load test data
test_data = pd.read_csv("artifacts/test_data.csv")
X_test = test_data.drop(columns=["Revenue"])
# Get first sample
sample = X_test.iloc[0].to_dict()
# Make prediction
response = requests.post(
"http://localhost:8000/predict",
json={"features": sample}
)
result = response.json()
print(f"Prediction: {result['prediction_label']}")
print(f"Confidence: {result['confidence']:.2%}")FastAPI provides automatic interactive documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
These interfaces allow you to:
- View all available endpoints
- See request/response schemas
- Test endpoints directly from the browser
- View detailed error messages
The API returns appropriate HTTP status codes:
200 OK: Successful prediction400 Bad Request: Invalid input data (wrong feature count, missing fields, etc.)500 Internal Server Error: Server error during prediction
Error Response Format:
{
"detail": "Error message describing what went wrong"
}The API expects 66 preprocessed features (indexed 0-65) after transformation:
- Cyclical encoding of Month (sin/cos)
- One-hot encoding of categorical variables
- Numerical features scaled/normalized
Note: The features must match the format produced by DataTransformation.transform_data().
The API currently allows all origins (allow_origins=["*"]). For production, configure specific origins:
app.add_middleware(
CORSMiddleware,
allow_origins=["https://your-frontend-domain.com"],
allow_credentials=True,
allow_methods=["POST", "GET"],
allow_headers=["*"],
)pip install gunicorn
gunicorn src.app:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000docker build -t purchase-predictor .
docker run -p 8000:8000 purchase-predictorConsider using environment variables for configuration:
API_HOST: Server host (default: 0.0.0.0)API_PORT: Server port (default: 8000)MODEL_PATH: Path to model file (default: models/model.pkl)LOG_LEVEL: Logging level (default: INFO)
Logs are written to logs/api.log with the following information:
- Model loading status
- Prediction requests (with feature counts)
- Prediction results (label and confidence)
- Errors and exceptions
- Add Prediction Logging: Store predictions in a database for drift detection
- Implement MLflow Tracking: Log model versions and experiments
- Add Authentication: Secure the API with API keys or OAuth
- Rate Limiting: Prevent API abuse
- Drift Detection: Monitor feature distributions
- Automated Retraining: Trigger retraining when drift is detected
- Ensure
models/model.pklexists - Run
python demo_train.py(orpython demo_training.py) to train the model first
- The API expects exactly 66 features (0-65)
- Ensure you're passing transformed features, not raw data
- Exclude the "Revenue" target column from test data
# Kill process on port 8000 (Windows)
netstat -ano | findstr :8000
taskkill /PID <PID> /F
# Kill process on port 8000 (Linux/Mac)
lsof -ti:8000 | xargs kill -9- FastAPI Documentation: https://fastapi.tiangolo.com/
- API Testing with Postman: https://www.postman.com/
- Python Requests Library: https://requests.readthedocs.io/