++++Data Science
May 2026×Notebook lesson
Notebook converted from Jupyter for blog publishing.
01-Serving-Model-as-API
Driptanil DattaSoftware Developer
Serving a Model as an API
NOTE: While we show this inside a Jupyter Notebook, you would probably never deploy something as a notebook in a real-world setting. Everything here is in one cell to reflect that this should be a .py file. We also included a duplicate .py file in this folder.
NOTE: You will need to install Flask to serve the API: https://flask.palletsprojects.com/en/2.0.x/installation/ (opens in a new tab)
pip install flask
or
conda install flask
api.py (Run this as a script as shown in the video, NOT from within a Jupyter Cell)
############################
######## IMPORTS ##########
##########################
from flask import Flask, request, jsonify
import joblib
import pandas as pd
# Create Flask App
app = Flask(__name__)
# Create API routing call
@app.route('/predict', methods=['POST'])
def predict():
# Get JSON Request
feat_data = request.json
# Convert JSON request to Pandas DataFrame
df = pd.DataFrame(feat_data)
# Match Column Na,es
df = df.reindex(columns=col_names)
# Get prediction
prediction = list(model.predict(df))
# Return JSON version of Prediction
return jsonify({'prediction': str(prediction)})
if __name__ == '__main__':
# LOADS MODEL AND FEATURE COLUMNS
model = joblib.load("final_model.pkl")
col_names = joblib.load("column_names.pkl")
app.run(debug=True)JSON Post Request
- POST to: http://127.0.0.1:5000/predict (opens in a new tab)
- Select Body
- Select Raw
- Select JSON(application/json)
- Supply JSON for Features: [{"TV":230.1,"radio":37.8,"newspaper":69.2}]