Turn AI Into Action: Serve Your Machine Learning Model with a REST API


In today’s world, everyone is talking about AI, from chatbots to self-driving cars; it seems like artificial intelligence is everywhere. Many people wonder how AI can make their everyday tasks easier, more efficient, or even smarter.
But here’s the catch: while countless people use AI-powered apps, only a few dare to build their own AI models from scratch.
If you’ve ever wanted to move beyond just using AI and actually create and deploy your own machine learning model, you’re in the right place. In this article, I’ll take you step-by-step through the exciting journey of training your first machine learning model and turning it into a real-world application by serving it with a REST API.
What We’re Building
We’ll build a complete machine learning pipeline from scratch:
Train a Machine Learning Model: Using real-world loan application data, we’ll train and compare three popular models: Logistic Regression, Decision Tree, and Random Forest.
Evaluate Model Performance: We’ll test each model to determine which one yields the most accurate predictions.
Save the Best Model: We’ll save the most precise model as a
.pkl
file for later use.Build a REST API with Flask: Using Flask, we’ll create a simple web service that loads the saved model and predicts loan approvals based on new input data.
Test the API: Finally, you’ll see how to send data to the API and get real-time predictions.
By the end, you’ll have a working ML model integrated with a REST API and a solid foundation for many AI-powered applications!
The Tech Stack
Here’s a rundown of the key technologies and libraries we’ll use in this project:
Python: The programming language used for data processing, model training, and API development.
Pandas: For data manipulation and analysis.
Scikit-learn: To build, train, and evaluate machine learning models like Logistic Regression, Decision Tree, and Random Forest.
Joblib: To save and load trained machine learning models efficiently.
Flask: A lightweight Python web framework used to build the REST API that serves our ML model.
Flask-CORS: To enable Cross-Origin Resource Sharing, allowing our API to be accessed from different domains (e.g., from a frontend app).
NumPy: For numerical operations and data handling.
This combination offers a powerful yet accessible stack, perfect for beginners looking to build real-world machine learning applications.
Prerequisites
Before we begin, make sure you have the following tools and setups ready:
Python (3.8 or higher): You'll need Python installed to run the ML training scripts and the Flask API.
pip (Python package manager):
This usually comes pre-installed with Python. You’ll use it to install project dependencies.
Check if it's installed:
pip --version
Code Editor: A good editor like VS Code makes development easier.
Basic Python & ML Knowledge: You don’t need to be a data science expert, but having a basic understanding of:
Python syntax
How machine learning works (input, training, prediction)
REST APIs (just the basics)
Project Structure
Here’s how I organized my project files for better modularity and clarity. This structure supports both backend (ML + Flask API) and frontend (React):
Loan Management System/
├── Frontend/ # Optional if you want to build UI for user input data
│ └── lms_frontend/ # React frontend app
│ ├── public/
│ ├── src/ # React source code
│ ├── package.json
│ ├── package-lock.json
│ └── README.md
├── venv/ # Python virtual environment
├── app.py # Flask REST API
├── LOAN SANCTION ASSESSMENT.py # ML training and evaluation script
├── loan_model.pkl # Saved trained model
├── train_data.csv # Training dataset
├── test_data.csv # Test dataset
└── requirements.txt # Python dependencies
Key Files:
LOAN SANCTION ASSESSMENT.py
: Contains all ML training logic (model selection, preprocessing, evaluation).loan_model.pkl
: The saved Random Forest model used for predictions.app.py
: Flask-based REST API that loads the model and handles prediction requests.train_data.csv
/test_data.csv
: Datasets used for training and validation.Frontend/lms_frontend/
: An optional React application (if you're building a UI for users to input data).
Setting Up Your Project Environment with venv
and Dependencies
Before diving into the code, it’s best practice to set up a virtual environment to isolate your project’s dependencies and avoid conflicts.
Step 1: Create a Virtual Environment
Navigate to your project directory and run:
python -m venv venv
This creates a folder named venv/
that contains your isolated Python environment.
Step 2: Activate the Virtual Environment
On macOS/Linux:
source venv/bin/activate
On Windows:
venv\Scripts\activate
You’ll see your terminal prompt change, indicating that the environment is active.
Step 3: Install Dependencies
With the environment activated, install all required packages using:
pip install -r requirements.txt
Your requirements.txt
file should look like this:
pandas>=1.0.0
scikit-learn>=0.24.0
joblib
flask
flask-cors==4.0.0
numpy
You can generate this file yourself after installing packages using:
pip freeze > requirements.txt
This makes it easy for anyone else (or future you) to set up the project quickly.
Time to Bring AI to Life
In today’s world of digital banking and financial automation, predicting loan approvals using machine learning can save time and reduce manual errors. Here, we are going to build a loan sanction prediction system using Python, train a Random Forest model, and expose it via a Flask REST API.
Step 1: Prepare and Explore Your Data
For this project, I used a simplified loan approval dataset (train_data.csv
) that contains applicant information like:
Income
Loan amount
Credit history
Education
Property area
Loan status (Approved or Not)
Our goal: Predict whether a loan should be approved based on the applicant's details.
Below are glimpses of the training data:
Step 2: Preprocess the Data
We start by loading your training and test data with pandas
. Clean and preprocess the data by encoding categorical features to numeric values using LabelEncoder
. This ensures the models can process the input correctly.
Load your dataset using
pandas
.Encode categorical columns into numeric using
LabelEncoder
.Split dataset into features (
X
) and target (Y
).Split into training and test sets using
train_test_split
where 80% is training data and 20% is testing data.
Here’s how the code uses LabelEncoder
from scikit-learn:
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
dataset = pd.read_csv("train_data.csv")
# Convert categorical columns to numeric
label_cols = ['Gender', 'Married', 'Education', 'Self_Employed', 'Property_Area', 'Loan_Status']
le = LabelEncoder()
for col in label_cols:
dataset[col] = le.fit_transform(dataset[col])
# Select features and target
X = dataset[['ApplicantIncome', 'CoapplicantIncome', 'LoanAmount', 'Loan_Amount_Term', 'Credit_History']]
y = dataset['Loan_Status']
# Train/test split
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Step 3: Train and Compare Multiple Machine Learning Models
Before finalizing a model, I experimented with three commonly used classifiers:
Logistic Regression
Decision Tree
Random Forest
Each model was trained using the same features:
ApplicantIncome
CoapplicantIncome
LoanAmount
Loan_Amount_Term
Credit_History
Here’s the evaluation setup:
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# Logistic Regression
model1 = LogisticRegression(max_iter=500)
model1.fit(x_train, y_train)
pred1 = model1.predict(x_test)
print('ACCURACY PERCENTAGE FOR LOGISTIC REGRESSION IS : ',(accuracy_score(y_test, pred1))*100,end='%\n')
# Decision Tree
model2 = DecisionTreeClassifier()
model2.fit(x_train, y_train)
pred2 = model2.predict(x_test)
print('ACCURACY PERCENTAGE FOR DECISION TREE IS : ',(accuracy_score(y_test, pred2))*100,end='%\n')
# Random Forest
model3 = RandomForestClassifier(n_estimators=100)
model3.fit(x_train, y_train)
pred3 = model3.predict(x_test)
print('ACCURACY PERCENTAGE FOR RONDOM FOREST IS : ',(accuracy_score(y_test, pred3))*100,end='%\n')
Accuracy Results (In My Case)
ACCURACY PERCENTAGE FOR LOGISTIC REGRESSION IS : 80.20833333333334%
ACCURACY PERCENTAGE FOR DECISION TREE IS : 78.125%
ACCURACY PERCENTAGE FOR RONDOM FOREST IS : 83.33333333333334%
After comparing results, I chose Random Forest as the final model because it provided the best accuracy and generalization across the test data.
Step 4: Save Your Trained Model
Use joblib
to save the best model for later use:
import joblib
joblib.dump(model3, 'loan_model.pkl')
Step 5: Build a REST API with Flask
Now that we have a model, let’s make it accessible via an API.
Install Flask:
pip install flask flask-cors
Create an API that:
Loads the saved model (
loan_model.pkl
).Receives new input data (loan application details) via POST requests.
Runs predictions using the model.
Returns the result as a JSON response.
Create app.py
:
from flask import Flask, request, jsonify
import joblib
import numpy as np
from flask_cors import CORS
# Load trained model
model = joblib.load('loan_model.pkl')
app = Flask(__name__)
CORS(app)
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
try:
features = np.array([[
data['ApplicantIncome'],
data['CoapplicantIncome'],
data['LoanAmount'],
data['Loan_Amount_Term'],
data['Credit_History']
]])
prediction = model.predict(features)
label = 'Approved' if prediction[0] == 1 else 'Not Approved'
return jsonify({'prediction': label})
except KeyError as e:
return jsonify({'error': f'Missing key: {e}'}), 400
if __name__ == '__main__':
app.run(debug=True)
Step 6: Test the API
You can start the Flask application using the command below:
python -m flask run
You can now test the API using Postman or curl
.
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"ApplicantIncome": 5000, "CoapplicantIncome": 1500, "LoanAmount": 120, "Loan_Amount_Term": 360, "Credit_History": 1}'
Response:
{
"prediction": "Approved"
}
Step 7: Add a Frontend with React (Optional)
While our Flask REST API is fully functional and can be tested using tools like Postman, you can take it a step further by building a React.js frontend to interact with your machine learning model.
This is completely optional, but if you're interested in building a user-friendly interface, React is a great choice.
What the React App Can Do
Collect loan applicant data (income, credit history, loan amount, etc.)
Send it as a POST request to your Flask API
Display the prediction result: Approved or Not Approved
React Project Structure (Inside /Frontend/lms_frontend/
)
Your directory might look like this:
Frontend/
└── lms_frontend/
├── public/
├── src/
├── package.json
└── README.md
Standalone LoanDetails
Page with API Communication
Here’s a standalone React component named LoanDetails
, designed to collect user input and send it to the Flask API for loan prediction:
import React, { useState } from 'react';
import './LoanDetails.css';
import axios from 'axios';
const LoanDetails = () => {
const [formData, setFormData] = useState({
ApplicantIncome: '',
CoapplicantIncome: '',
LoanAmount: '',
Loan_Amount_Term: '',
Credit_History: ''
});
const [prediction, setPrediction] = useState('');
const [error, setError] = useState('');
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = async (e) => {
e.preventDefault();
setPrediction('');
setError('');
try {
const response = await axios.post('http://localhost:5000/predict', {
...formData,
ApplicantIncome: Number(formData.ApplicantIncome),
CoapplicantIncome: Number(formData.CoapplicantIncome),
LoanAmount: Number(formData.LoanAmount),
Loan_Amount_Term: Number(formData.Loan_Amount_Term),
Credit_History: Number(formData.Credit_History)
});
setPrediction(response.data.prediction);
} catch (err) {
if (err.response && err.response.data.error) {
setError(err.response.data.error);
} else {
setError('An error occurred while making the request.');
}
}
};
return (
<div className="loan-form-container">
<h1>Loan Approval Prediction</h1>
<form onSubmit={handleSubmit} className="loan-form">
<input
type="number"
name="ApplicantIncome"
placeholder="Applicant Income"
value={formData.ApplicantIncome}
onChange={handleChange}
required
/>
<input
type="number"
name="CoapplicantIncome"
placeholder="Coapplicant Income"
value={formData.CoapplicantIncome}
onChange={handleChange}
required
/>
<input
type="number"
name="LoanAmount"
placeholder="Loan Amount"
value={formData.LoanAmount}
onChange={handleChange}
required
/>
<input
type="number"
name="Loan_Amount_Term"
placeholder="Loan Amount Term"
value={formData.Loan_Amount_Term}
onChange={handleChange}
required
/>
<select
name="Credit_History"
value={formData.Credit_History}
onChange={handleChange}
required
>
<option value="">Select Credit History</option>
<option value="1">Good (1)</option>
<option value="0">Bad (0)</option>
</select>
<button type="submit">Predict</button>
</form>
{prediction && <div className="result success">Prediction: {prediction}</div>}
{error && <div className="result error">{error}</div>}
</div>
);
};
export default LoanDetails;
Just make sure CORS is enabled in Flask (which we already did using Flask-CORS
)!
UI Screen after running the application:
Step 8: Next Steps & Tips
Experiment with adding more features to your model.
Try other ML algorithms to improve accuracy.
Containerize your app using Docker for easy deployment.
Final Thoughts
In this article, you’ve learned how to:
Train multiple machine learning models and choose the most accurate one
Save your trained model for reuse with
joblib
Build a REST API using Flask to serve real-time predictions
Manage your Python environment and dependencies using
venv
andrequirements.txt
With this foundation, you're now equipped to build and deploy real-world AI applications that go beyond experimentation into production.
Wrapping Up
🎉 Congratulations! You've successfully built a complete machine learning pipeline from training and evaluating models, saving the best one, to serving predictions via a REST API.
This is the exact structure used in many real-world AI solutions, turning raw data into decisions that power apps, services, and systems.
What You Can Build Next:
Add advanced preprocessing for better model accuracy
Fine-tune hyperparameters or explore new algorithms
Secure your API with authentication or rate-limiting
Deploy everything to the cloud (e.g., AWS, Heroku, or Render)
AI isn’t just a buzzword anymore; it’s a tool you can wield. And now, you know how to turn your AI ideas into action.
#MachineLearning #AI #Python #DataScience #MLDeployment #Flask #RestAPI #RandomForest #ScikitLearn #ReactJS #DecisionTree
Subscribe to my newsletter
Read articles from Himanshu Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Himanshu Jha
Himanshu Jha
Software Developer with 4+ years of experience in application development, proficient in Python, Java, ReactJS, and React Native. Successfully delivered several complex applications, demonstrating strong problem-solving and technical expertise.