We use a Flask API to let other programs ask our machine learning model for predictions easily. It acts like a friendly waiter taking requests and giving answers.
Flask API for model serving in ML Python
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/predict', methods=['POST']) def predict(): data = request.get_json() # process data and get prediction prediction = model.predict(data['input']) return jsonify({'prediction': prediction.tolist()}) if __name__ == '__main__': app.run(debug=True)
Use @app.route to define the URL path and HTTP method.
Use request.get_json() to get input data sent as JSON.
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/hello') def hello(): return 'Hello, world!' if __name__ == '__main__': app.run()
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/predict', methods=['POST']) def predict(): data = request.get_json() number = data['number'] result = number * 2 return jsonify({'result': result}) if __name__ == '__main__': app.run()
This Flask app trains a model on iris flower data. It listens for POST requests at /predict with flower features and returns the predicted species name.
from flask import Flask, request, jsonify from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import numpy as np # Train a simple model iris = load_iris() X, y = iris.data, iris.target model = RandomForestClassifier() model.fit(X, y) app = Flask(__name__) @app.route('/predict', methods=['POST']) def predict(): data = request.get_json() features = np.array(data['features']).reshape(1, -1) prediction = model.predict(features)[0] species = iris.target_names[prediction] return jsonify({'prediction': species}) if __name__ == '__main__': app.run(debug=False)
Flask runs a simple web server that listens for requests on your computer.
Use JSON format to send and receive data easily between client and server.
For production, use a more robust server like Gunicorn and secure your API.
Flask API lets you share your ML model so others can get predictions over the web.
Define routes with @app.route and handle data with JSON.
Test your API by sending POST requests with input data and reading the JSON response.
Practice
Solution
Step 1: Understand Flask's role
Flask is a lightweight web framework used to build web applications and APIs.Step 2: Connect Flask to model serving
In machine learning, Flask is used to create an API endpoint where clients can send input data and receive model predictions.Final Answer:
To create a web API that allows clients to send data and get predictions -> Option BQuick Check:
Flask for API = Create prediction endpoint [OK]
- Thinking Flask trains models
- Confusing Flask with data storage tools
- Assuming Flask is for data visualization
Solution
Step 1: Recall Flask route syntax
Flask routes use @app.route decorator with a path and a list of HTTP methods.Step 2: Identify correct method for sending data
POST method is used to send data to the server for processing, suitable for model prediction.Final Answer:
@app.route('/predict', methods=['POST']) -> Option CQuick Check:
POST method for data sending = Correct route [OK]
- Using GET instead of POST for sending data
- Missing 'methods' keyword or using wrong syntax
- Assuming default route accepts POST
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
result = sum(data['input'])
return jsonify({'prediction': result})Solution
Step 1: Extract input data from JSON
The code uses request.get_json() to get {'input': [1, 2, 3]} and accesses data['input'] which is [1, 2, 3].Step 2: Calculate sum of input list
sum([1, 2, 3]) equals 6, which is stored in result and returned as JSON.Final Answer:
{"prediction": 6} -> Option AQuick Check:
Sum of [1,2,3] = 6 [OK]
- Returning the list instead of sum
- Concatenating numbers as string
- Missing JSON key causing KeyError
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
data = request.json()
prediction = model.predict(data['input'])
return jsonify({'prediction': prediction.tolist()})Solution
Step 1: Check how JSON data is accessed
request.json() is incorrect; Flask uses request.get_json() to parse JSON body.Step 2: Confirm other parts are correct
methods=['POST'] is correct for sending data; .tolist() is valid if prediction is numpy array; @app.run() is not a decorator.Final Answer:
Change request.json() to request.get_json() -> Option AQuick Check:
Use request.get_json() to parse JSON [OK]
- Using request.json() instead of get_json()
- Confusing HTTP methods for data sending
- Misusing Flask decorators
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
# Prepare input for model
input_features = ???
prediction = model.predict(input_features)
return jsonify({'prediction': prediction.tolist()})Solution
Step 1: Understand model input shape
Scikit-learn models expect 2D arrays: shape (n_samples, n_features). A single sample must be wrapped in an outer list.Step 2: Prepare input accordingly
Wrapping data['features'] (a list of features) inside another list creates a 2D list suitable for prediction.Final Answer:
input_features = [data['features']] # Wrap list inside another list -> Option DQuick Check:
Wrap features in list for 2D input [OK]
- Passing 1D list directly causing shape errors
- Using only first element losing features
- Calling .tolist() on a list (already a list)
Ready to prove it?
Pass the test and this pattern moves unknown
