হোম/Roadmap/Chapter 1.02
Phase 1 · Chapter 1.02

REST API for ML

Model file disk-এ আছে — এবার সেটাকে network-এর মাধ্যমে accessible করার পালা। REST-ই এর সবচেয়ে common pattern।

Hook

Model + Network = Service

Mobile app, frontend, অন্য microservice — সবাই model-এর prediction চায়। সরাসরি model file পাঠানো অসম্ভব। সমাধান: model কে একটি REST endpoint-এর পেছনে রাখা।

Concept

REST-এর মৌলিক চারটি ধারণা

  • Resource — যেমন /predictions, /models
  • HTTP method — GET, POST, PUT, DELETE।
  • Status code — 200, 400, 422, 500।
  • Stateless — প্রতিটি request স্বনির্ভর।
Step-by-step

ML API contract design

jsonproduction
POST /predict
Request:
{
  "features": [5.1, 3.5, 1.4, 0.2]
}

Response 200:
{
  "class": 0,
  "label": "setosa",
  "probability": 0.97,
  "model_version": "v1.2.0"
}

ব্যাখ্যা: ML response-এ model_version দেওয়া important — debugging ও A/B testing-এ লাগবে।

Code

Minimal Flask example

pythonproduction
from flask import Flask, request, jsonify
import joblib

app = Flask(__name__)
model = joblib.load("model.joblib")
LABELS = ["setosa", "versicolor", "virginica"]

@app.post("/predict")
def predict():
    data = request.get_json()
    features = data.get("features")
    if not features or len(features) != 4:
        return jsonify({"error": "features must be length 4"}), 400
    cls = int(model.predict([features])[0])
    return jsonify({"class": cls, "label": LABELS[cls], "model_version": "v1.0.0"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

ব্যাখ্যা: Input validation, structured response, error status — এই তিনটি যেকোনো ML API-এর non-negotiable।

Intuition

ML endpoint design pattern

  • /predict — single prediction।
  • /predict/batch — bulk inference।
  • /health — liveness probe।
  • /metadata — model version, features schema।
Real-world

Industry pattern

  • OpenAI API — REST + JSON, stateless।
  • Hugging Face Inference API — model-as-endpoint।
  • AWS SageMaker — invocations endpoint per model।
Common Mistakes

যেসব ভুল বেশি হয়

  • Input validate না করা — crash বা bad prediction।
  • Synchronous heavy model একই thread-এ — throughput কম।
  • Model version response-এ না দেওয়া — debugging কঠিন।
  • Error message-এ stack trace expose — security risk।
Practice Tasks

অনুশীলন

  1. উপরের Flask API চালু করে curl দিয়ে test করুন।
  2. /predict/batch endpoint যোগ করুন।
  3. /health এবং /metadata endpoint যোগ করুন।
  4. Invalid input দিলে 422 status return করুন।
Mini Project

Mini Project — Iris REST Service

একটি Flask app বানান যেখানে: /predict, /predict/batch,/health, /metadata — চারটি endpoint থাকবে।curl ও Postman দিয়ে test করুন। GitHub-এ push করুনREADME.md-এ contract সহ।

Summary

এই chapter থেকে যা শিখলাম

  • REST = resource + method + status + stateless।
  • ML API-তে version, validation, structured error obligatory।
  • Health ও metadata endpoint observability-র ভিত্তি।