Building REST APIs for Scikit-learn Models with Flask

REST APIs allow machine learning models to be served as web services. Using Flask, a lightweight Python web framework, Scikit-learn models can be hosted and made accessible to client applications for real-time predictions.

Key Characteristics

  • Enables model interaction via HTTP requests
  • Lightweight and easy to implement
  • Ideal for prototyping and small-scale deployments
  • Scalable with tools like Gunicorn and Nginx

Basic Rules

  • Always load pre-trained models with consistent preprocessing
  • Accept input in JSON format and return JSON responses
  • Ensure proper input validation and error handling
  • Use secure methods for public-facing APIs

Syntax Table

SL NO Task Syntax Example Description
1 Import Flask from flask import Flask, request, jsonify Loads Flask and HTTP utility functions
2 Initialize App app = Flask(__name__) Sets up the Flask web app
3 Define Route @app.route('/predict', methods=['POST']) Creates prediction endpoint
4 Parse Input data = request.get_json(force=True) Reads JSON payload from client
5 Return Prediction return jsonify({'prediction': prediction}) Sends back model result as JSON

Syntax Explanation

1. Import Flask

What is it?
Loads the Flask library and related modules to handle web server functionality.

Syntax:

from flask import Flask, request, jsonify

Explanation:

  • Flask is the class used to create the web server
  • request allows access to incoming data
  • jsonify formats response as JSON

2. Initialize App

What is it?
Creates an instance of the Flask app.

Syntax:

app = Flask(__name__)

Explanation:

  • Required to start the Flask application
  • __name__ helps Flask locate resources

3. Define Route

What is it?
Maps a URL endpoint to a Python function for client access.

Syntax:

@app.route('/predict', methods=['POST'])

Explanation:

  • Tells Flask to listen for POST requests at /predict
  • Used to process prediction input

4. Parse Input

What is it?
Reads incoming JSON data sent by the client.

Syntax:

data = request.get_json(force=True)

Explanation:

  • Extracts JSON payload from HTTP request
  • force=True ensures parsing even without proper header

5. Return Prediction

What is it?
Formats model output into JSON and sends it back to the client.

Syntax:

return jsonify({'prediction': prediction})

Explanation:

  • Converts Python dictionary to JSON
  • Automatically sets content-type and headers

Real-Life Project: Iris Species Classification API

Project Overview

Deploy a trained Scikit-learn classifier to predict the species of Iris flowers based on input features.

Code Example

from flask import Flask, request, jsonify
from joblib import load
import numpy as np

app = Flask(__name__)
model = load('iris_model.pkl')

@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json(force=True)
    features = np.array(data['features']).reshape(1, -1)
    prediction = model.predict(features)[0]
    return jsonify({'prediction': prediction})

if __name__ == '__main__':
    app.run(debug=True)

Expected Output

  • JSON prediction for each incoming POST request
  • Response example: { "prediction": "setosa" }

Common Mistakes to Avoid

  • ❌ Not validating shape or type of incoming data
  • ❌ Failing to catch prediction exceptions
  • ❌ Hardcoding logic without configuration or modularity

Further Reading Recommendation

📘 Hands-On Python and Scikit-Learn: A Practical Guide to Machine Learning by Sarful Hassan

🔗 Available on Amazon