Skip to content

Latest commit

 

History

History
300 lines (235 loc) · 6.43 KB

API_USAGE.md

File metadata and controls

300 lines (235 loc) · 6.43 KB

that # Real-Time Purchase Prediction API - Usage Guide

Overview

This FastAPI application provides real-time purchase prediction for e-commerce sessions. The API accepts preprocessed feature vectors and returns predictions with confidence scores.

Starting the API Server

Method 1: Using Uvicorn (Recommended for Development)

python -m uvicorn src.app:app --reload --host 0.0.0.0 --port 8000

Method 2: Using Python Directly

python src/app.py

The server will start on http://localhost:8000

Available Endpoints

1. Root Endpoint

GET /

Returns basic API information.

Response:

{
  "message": "Real-Time Purchase Prediction API",
  "docs": "/docs",
  "health": "/health"
}

2. Health Check

GET /health

Check if the API and model are loaded and ready.

Response:

{
  "status": "healthy",
  "model_loaded": true,
  "api_version": "1.0.0"
}

3. Single Prediction

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)

4. Batch Prediction

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
  }
]

Testing the API

Using the Demo Script

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.py

Using cURL

Health Check:

curl http://localhost:8000/health

Single Prediction:

curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d @sample_prediction_request.json

Using Python Requests

import 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%}")

Interactive API Documentation

FastAPI provides automatic interactive documentation:

These interfaces allow you to:

  • View all available endpoints
  • See request/response schemas
  • Test endpoints directly from the browser
  • View detailed error messages

Error Handling

The API returns appropriate HTTP status codes:

  • 200 OK: Successful prediction
  • 400 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"
}

Feature Format

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().

Production Considerations

CORS Configuration

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=["*"],
)

Running with Gunicorn (Production)

pip install gunicorn
gunicorn src.app:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

Docker Deployment

docker build -t purchase-predictor .
docker run -p 8000:8000 purchase-predictor

Environment Variables

Consider 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)

Monitoring

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

Next Steps

  1. Add Prediction Logging: Store predictions in a database for drift detection
  2. Implement MLflow Tracking: Log model versions and experiments
  3. Add Authentication: Secure the API with API keys or OAuth
  4. Rate Limiting: Prevent API abuse
  5. Drift Detection: Monitor feature distributions
  6. Automated Retraining: Trigger retraining when drift is detected

Troubleshooting

Model Not Loading

  • Ensure models/model.pkl exists
  • Run python demo_train.py (or python demo_training.py) to train the model first

Wrong Feature Count

  • 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

Port Already in Use

# 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

Additional Resources