What if your smart model could answer questions instantly for anyone, anywhere, without you lifting a finger?
Why Flask API for model serving in ML Python? - Purpose & Use Cases
Imagine you built a smart model that predicts house prices. Now, you want your friends or apps to use it anytime. Without an API, you'd have to run your model on your computer and share results manually every time someone asks.
This manual way is slow and tiring. You must run the model yourself, copy results, and send them back. It's easy to make mistakes, and you can't help many people at once. Plus, your model can't work 24/7 without you.
Using a Flask API, you wrap your model inside a small web service. This service listens for requests, runs the model automatically, and sends back answers instantly. It works all day, handles many users, and removes all manual steps.
result = model.predict(data)
print(result)from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/predict', methods=['POST']) def predict(): data = request.json result = model.predict(data) return jsonify(result.tolist())
You can share your model with anyone, anywhere, anytime, making your smart solution instantly useful and scalable.
A company uses a Flask API to serve a fraud detection model. When a payment is made, their app sends data to the API, which quickly replies if the payment looks suspicious, helping stop fraud in real time.
Manual sharing of model results is slow and error-prone.
Flask API automates model access via simple web requests.
This makes your model available anytime to many users easily.
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
