Serve a Model with a Flask REST API

Deep Learning with Keras and TensorFlow 11 min min read Updated: Nov 16, 2026 Advanced
Serve a Model with a Flask REST API
Advanced Topic 3 of 7

The Plan

We will wrap a trained image classifier in a small web service. A client uploads a picture, the server runs the model and replies with JSON such as the predicted class and confidence.

Install

bash pip install flask pillow

The App

Create a file named app.py.

python import io import numpy as np import keras from flask import Flask, request, jsonify from PIL import Image app = Flask(__name__) # Load the model ONCE when the server starts, not on every request model = keras.models.load_model("fashion_cnn.keras") CLASS_NAMES = ["T-shirt", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"] def prepare(image_bytes): img = Image.open(io.BytesIO(image_bytes)).convert("L") # grayscale img = img.resize((28, 28)) arr = np.array(img).astype("float32") / 255.0 return arr.reshape(1, 28, 28, 1) @app.route("/health") def health(): return jsonify(status="ok") @app.route("/predict", methods=["POST"]) def predict(): if "file" not in request.files: return jsonify(error="Send an image in the 'file' field"), 400 try: x = prepare(request.files["file"].read()) except Exception: return jsonify(error="Could not read the image"), 400 probs = model.predict(x, verbose=0)[0] top = int(np.argmax(probs)) return jsonify( label=CLASS_NAMES[top], confidence=round(float(probs[top]), 4), ) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000)

Run It

bash python app.py

Test It

bash curl -X POST -F "file=@shoe.png" http://localhost:5000/predict
python import requests with open("shoe.png", "rb") as f: r = requests.post("http://localhost:5000/predict", files={"file": f}) print(r.json()) # {'confidence': 0.97, 'label': 'Sneaker'}

Points to Remember

  • Load the model once at startup. Loading it per request is very slow
  • Use the same preprocessing as in training (size, color mode, scaling)
  • Validate uploads: check the file exists, limit the file size and handle errors
  • Never trust file names from users. Read the bytes, do not save them with the given name

Going to Production

The built-in Flask server is for development only. For real traffic use a production server such as Gunicorn behind a reverse proxy, or package everything in Docker.

bash pip install gunicorn gunicorn -w 2 -b 0.0.0.0:5000 app:app
Tip: Add the /health endpoint. Hosting platforms use it to check that your service is alive.

Conclusion

A Flask wrapper is the quickest way to make your model useful for other programs. Load the model once, preprocess the same way and return clear JSON.

Quick Summary: Create /predict, load the model at startup, preprocess the upload and return JSON. Use Gunicorn in production.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators