A secure FastAPI-based REST API for predicting customer churn using machine learning models.
first read the Customer_Churn_Prediction_using_ML_v5.ipynb to create churn prediction model
first read the Customer_Churn_Prediction_using_ML_v5.ipynb to create churn prediction model
pip install -r requirements.txtpython generate_ssl_cert.pyIf the step above fails on Windows due to missing openssl.cnf, the script now bundles an in-project config and should work. The script now always writes server.crt and server.key into the project folder (ignores Conda SSL_CERT_FILE). You can also skip SSL and use HTTP.
python start_api.pylocalhost or 127.0.0.1 in your browser, NOT 0.0.0.0!
The server binds to 0.0.0.0:8000 but you access it via:
- Web UI:
https://localhost:8000/ui(orhttp://if no SSL) - API Docs:
https://localhost:8000/docs - ReDoc:
https://localhost:8000/redoc - Health:
https://localhost:8000/health - Default Credentials:
admin/churn2024!
Self-Signed Certificate: Your browser will warn you about the certificate. Click "Advanced" β "Proceed to localhost" to continue. This is normal for development.
For a detailed walkthrough, see QUICK_START.md
- β Secure Authentication - Basic Auth with configurable credentials
- β TLS/SSL Encryption - Secure data transmission
- β Input Validation - Comprehensive data validation using Pydantic
- β Batch Processing - Predict multiple customers at once
- β Health Monitoring - Built-in health check endpoints
- β Interactive Documentation - Swagger UI and ReDoc
- β Error Handling - Detailed error messages and logging
| Endpoint | Method | Description | Auth Required |
|---|---|---|---|
/ |
GET | API information | No |
/ui |
GET | Web UI for manual testing | No |
/health |
GET | Health check | No |
/predict |
POST | Single customer prediction | Yes |
/predict/batch |
POST | Batch prediction (up to 100) | Yes |
/model/info |
GET | Model information | Yes |
/docs |
GET | Swagger UI documentation | No |
/redoc |
GET | ReDoc documentation | No |
import requests
from requests.auth import HTTPBasicAuth
# API configuration
API_URL = "https://localhost:8000"
auth = HTTPBasicAuth("admin", "churn2024!")
# Customer data
customer_data = {
"gender": "Female",
"SeniorCitizen": 0,
"Partner": "No",
"Dependents": "No",
"tenure": 42,
"PhoneService": "Yes",
"MultipleLines": "No phone service",
"InternetService": "DSL",
"OnlineSecurity": "Yes",
"OnlineBackup": "Yes",
"DeviceProtection": "No",
"TechSupport": "No",
"StreamingTV": "No internet service",
"StreamingMovies": "No internet service",
"Contract": "Two year",
"PaperlessBilling": "No",
"PaymentMethod": "Electronic check",
"MonthlyCharges": 38.28,
"TotalCharges": 1607.76
}
# Make prediction
response = requests.post(
f"{API_URL}/predict",
json=customer_data,
auth=auth,
verify=False # For self-signed certificates
)
result = response.json()
print(f"Prediction: {result['prediction']}")
print(f"Confidence: {result['confidence']:.3f}")curl -X POST "https://localhost:8000/predict" \
-H "Content-Type: application/json" \
-u "admin:churn2024!" \
-k \
-d '{
"gender": "Female",
"SeniorCitizen": 0,
"Partner": "No",
"Dependents": "No",
"tenure": 42,
"PhoneService": "Yes",
"MultipleLines": "No phone service",
"InternetService": "DSL",
"OnlineSecurity": "Yes",
"OnlineBackup": "Yes",
"DeviceProtection": "No",
"TechSupport": "No",
"StreamingTV": "No internet service",
"StreamingMovies": "No internet service",
"Contract": "Two year",
"PaperlessBilling": "No",
"PaymentMethod": "Electronic check",
"MonthlyCharges": 38.28,
"TotalCharges": 1607.76
}'Run the comprehensive test suite:
python test_api.pyThis will test:
- All API endpoints
- Authentication
- Input validation
- Batch processing
- Performance metrics
# Custom credentials
export API_USERNAME="your_username"
export API_PASSWORD="your_secure_password"
# SSL configuration
export SSL_CERT_FILE="/path/to/certificate.crt"
export SSL_KEY_FILE="/path/to/private.key"- Use certificates from trusted CA
- Change default credentials
- Implement rate limiting
- Use reverse proxy (nginx/Apache)
- Enable request logging
- Regular security updates
βββ churn_prediction_api.py # Main FastAPI application
βββ generate_ssl_cert.py # SSL certificate generator
βββ start_api.py # API startup script
βββ test_api.py # Comprehensive test suite
βββ requirements.txt # Python dependencies
βββ API_DOCUMENTATION.md # Detailed documentation
βββ README_API.md # This file
βββ server.crt # SSL certificate (generated)
βββ server.key # SSL private key (generated)
βββ customer_churn_model_rfc_v2.pkl # Trained model
βββ encoders.pkl # Feature encoders
-
SSL Certificate Errors
python generate_ssl_cert.py
-
Model Loading Errors
- Ensure model files exist in the same directory
- Check file permissions
-
Port Already in Use
# Kill process on port 8000 lsof -ti:8000 | xargs kill -9
-
Authentication Errors
- Verify credentials:
admin/churn2024! - Check environment variables
- Verify credentials:
The API logs to console. For production, configure file logging:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('api.log'),
logging.StreamHandler()
]
)- Single Prediction: ~50-100ms
- Batch Prediction: ~10-20ms per customer
- SSL Overhead: ~10-20% latency increase
- Memory Usage: ~100-200MB (model + dependencies)
python start_api.pypip install gunicorn
gunicorn churn_prediction_api:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 --keyfile server.key --certfile server.crtFROM python:3.9-slim
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
EXPOSE 8000
CMD ["python", "start_api.py"]For issues or questions:
- Check the detailed documentation
- Run the test suite:
python test_api.py - Check API logs for error details
- Verify model files are present and accessible
This project is part of a machine learning assessment for customer churn prediction.