Skip to main content

Lesson 9 of 12

Step 8: Simple Web API

The final step to a real AI application is wrapping it in a web API so other systems can use it. Here we show the structure using Flask.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Serving the Model as an API

Serving the Model as an API
# Simple Flask API for the spam classifier
# Save this as app.py and run: python app.py
# Install Flask first: pip install flask

# NOTE: This shows the structure. Run it in your own Python environment.

api_code = """
from flask import Flask, request, jsonify
import joblib

app = Flask(__name__)

# Load model and vectorizer at startup
model = joblib.load("spam_classifier.pkl")
vectorizer = joblib.load("spam_vectorizer.pkl")

@app.route("/predict", methods=["POST"])
def predict():
    # Get email text from request
    data = request.get_json()
    email_text = data.get("email", "")
    
    if not email_text:
        return jsonify({"error": "No email text provided"}), 400
    
    # Make prediction
    features = vectorizer.transform([email_text])
    prediction = model.predict(features)[0]
    probabilities = model.predict_proba(features)[0]
    confidence = float(max(probabilities))
    
    return jsonify({
        "email": email_text,
        "prediction": "spam" if prediction == 1 else "not_spam",
        "confidence": round(confidence, 3),
        "spam_probability": round(float(probabilities[1]), 3),
    })

@app.route("/health", methods=["GET"])
def health():
    return jsonify({"status": "ok", "model": "spam_classifier_v1"})

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)
"""

print("Flask API Structure:")
print(api_code)
print()
print("To test the API, send a POST request:")
print()

# Simulate an API request/response
request_body = {"email": "Congratulations! You won a free iPhone! Click here!"}
response_body = {
    "email": "Congratulations! You won a free iPhone! Click here!",
    "prediction": "spam",
    "confidence": 0.94,
    "spam_probability": 0.94,
}

print(f"POST /predict")
print(f"Request:  {request_body}")
print(f"Response: {response_body}")
Diagram
Loading diagram…

Educational visual guide for step 8 simple web api.

The Complete AI Application Stack

  • Data layer: raw emails stored in a database or CSV file
  • Feature layer: CountVectorizer or TfidfVectorizer converts text to numbers
  • Model layer: Naive Bayes or Logistic Regression trained on labeled examples
  • Persistence layer: joblib saves and loads the trained model and vectorizer
  • API layer: Flask or FastAPI exposes the model as an HTTP endpoint
  • Client layer: any application (email client, frontend, mobile app) sends requests and receives predictions
  • Monitoring layer: log predictions, track accuracy over time, retrain when needed

Key Takeaways

  • The final step to a real AI application is wrapping it in a web API so other systems can use it.
  • Data layer: raw emails stored in a database or CSV file
  • Feature layer: CountVectorizer or TfidfVectorizer converts text to numbers
  • Model layer: Naive Bayes or Logistic Regression trained on labeled examples

Topics in This Module

0/12 done