Bird
Raised Fist0
ML Pythonml~20 mins

Flask API for model serving in ML Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Model Serving Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Flask API response code?
Consider a Flask API that loads a trained model and predicts the class for input data. What will be the JSON response when sending input data [5.1, 3.5, 1.4, 0.2] to this endpoint?
ML Python
from flask import Flask, request, jsonify
import numpy as np
import pickle

app = Flask(__name__)

# Load model
with open('iris_model.pkl', 'rb') as f:
    model = pickle.load(f)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.json['data']
    arr = np.array(data).reshape(1, -1)
    pred = model.predict(arr)
    return jsonify({'prediction': int(pred[0])})
A{"prediction": 0}
B{"prediction": "setosa"}
C{"prediction": 1}
D{"error": "Invalid input"}
Attempts:
2 left
💡 Hint
The model is trained on Iris dataset where class 0 corresponds to 'setosa'. The input matches typical setosa features.
❓ Model Choice
intermediate
2:00remaining
Which model type is best suited for this Flask API serving handwritten digit recognition?
You want to serve a model via Flask API that recognizes handwritten digits (0-9) from 28x28 grayscale images. Which model type below is most appropriate for this task?
AA k-means clustering model
BA linear regression model
CA decision tree classifier
DA convolutional neural network (CNN)
Attempts:
2 left
💡 Hint
Consider the input type and the need to capture spatial features in images.
❓ Hyperparameter
advanced
2:00remaining
Which hyperparameter tuning improves Flask API model latency the most?
You deployed a deep learning model in a Flask API. The API latency is high. Which hyperparameter tuning below will most likely reduce prediction latency?
AIncrease the number of layers in the model
BReduce model size by pruning or quantization
CIncrease batch size during training
DIncrease learning rate during training
Attempts:
2 left
💡 Hint
Think about what affects model size and inference speed.
🔧 Debug
advanced
2:00remaining
Why does this Flask API code raise a KeyError?
This Flask API code raises a KeyError when a POST request is sent. What is the cause?
ML Python
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    data = request.json['input']
    # model prediction code here
    return jsonify({'result': 'ok'})
AThe route should accept GET instead of POST
BFlask app is missing debug=True
CThe JSON payload does not contain the key 'input'
DThe jsonify function is used incorrectly
Attempts:
2 left
💡 Hint
Check the JSON keys sent in the request body.
❓ Metrics
expert
2:00remaining
Which metric best evaluates a Flask API model for imbalanced binary classification?
Your Flask API serves a model that predicts rare disease presence (positive class is 1% of data). Which metric below is best to evaluate model performance?
AF1-score
BPrecision
CRecall
DAccuracy
Attempts:
2 left
💡 Hint
Consider a metric that balances false positives and false negatives in imbalanced data.

Practice

(1/5)
1. What is the main purpose of using Flask in model serving for machine learning?
easy
A. To train machine learning models faster
B. To create a web API that allows clients to send data and get predictions
C. To visualize data in charts and graphs
D. To store large datasets efficiently

Solution

  1. Step 1: Understand Flask's role

    Flask is a lightweight web framework used to build web applications and APIs.
  2. 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.
  3. Final Answer:

    To create a web API that allows clients to send data and get predictions -> Option B
  4. Quick Check:

    Flask for API = Create prediction endpoint [OK]
Hint: Flask makes your model accessible via web requests [OK]
Common Mistakes:
  • Thinking Flask trains models
  • Confusing Flask with data storage tools
  • Assuming Flask is for data visualization
2. Which of the following is the correct way to define a Flask route for a POST request to serve a model prediction?
easy
A. @app.route('/predict', methods=['GET'])
B. @app.route('/predict')
C. @app.route('/predict', methods=['POST'])
D. @app.route('/predict', method='POST')

Solution

  1. Step 1: Recall Flask route syntax

    Flask routes use @app.route decorator with a path and a list of HTTP methods.
  2. Step 2: Identify correct method for sending data

    POST method is used to send data to the server for processing, suitable for model prediction.
  3. Final Answer:

    @app.route('/predict', methods=['POST']) -> Option C
  4. Quick Check:

    POST method for data sending = Correct route [OK]
Hint: Use methods=['POST'] to accept data in Flask route [OK]
Common Mistakes:
  • Using GET instead of POST for sending data
  • Missing 'methods' keyword or using wrong syntax
  • Assuming default route accepts POST
3. Given the Flask code snippet below, what will be the output when a POST request with JSON {"input": [1, 2, 3]} is sent?
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})
medium
A. {"prediction": 6}
B. {"prediction": [1, 2, 3]}
C. {"prediction": 123}
D. Error: KeyError

Solution

  1. 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].
  2. Step 2: Calculate sum of input list

    sum([1, 2, 3]) equals 6, which is stored in result and returned as JSON.
  3. Final Answer:

    {"prediction": 6} -> Option A
  4. Quick Check:

    Sum of [1,2,3] = 6 [OK]
Hint: Sum list input to get prediction value [OK]
Common Mistakes:
  • Returning the list instead of sum
  • Concatenating numbers as string
  • Missing JSON key causing KeyError
4. Identify the error in the following Flask API code for model serving and select the fix:
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()})
medium
A. Change request.json() to request.get_json()
B. Change methods=['POST'] to methods=['GET']
C. Remove .tolist() from prediction
D. Add @app.run() after function

Solution

  1. Step 1: Check how JSON data is accessed

    request.json() is incorrect; Flask uses request.get_json() to parse JSON body.
  2. 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.
  3. Final Answer:

    Change request.json() to request.get_json() -> Option A
  4. Quick Check:

    Use request.get_json() to parse JSON [OK]
Hint: Use request.get_json() to read JSON body [OK]
Common Mistakes:
  • Using request.json() instead of get_json()
  • Confusing HTTP methods for data sending
  • Misusing Flask decorators
5. You want to serve a scikit-learn model using Flask. The model expects input features as a 2D list. Which approach correctly prepares the input inside the Flask route before prediction?
@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()})
hard
A. input_features = data['features'].tolist() # Convert to list
B. input_features = data['features'] # Use list directly
C. input_features = data['features'][0] # Use first element only
D. input_features = [data['features']] # Wrap list inside another list

Solution

  1. 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.
  2. Step 2: Prepare input accordingly

    Wrapping data['features'] (a list of features) inside another list creates a 2D list suitable for prediction.
  3. Final Answer:

    input_features = [data['features']] # Wrap list inside another list -> Option D
  4. Quick Check:

    Wrap features in list for 2D input [OK]
Hint: Wrap single feature list in another list for 2D input [OK]
Common Mistakes:
  • Passing 1D list directly causing shape errors
  • Using only first element losing features
  • Calling .tolist() on a list (already a list)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard