Step-by-step guide: Build a web app to interact with your ML model using sample code, tips & best practices.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Example using Flask
from flask import Flask, request, jsonify
import joblib // joblib allows you to load serialized ML models easily
app = Flask(**name**)
model = joblib.load('path/to/your/model.pkl') // Load the trained machine learning model
// Define an endpoint for predictions
@app.route('/predict', methods=['POST'])
def predict():
data = request.get\_json() // Get JSON input from client
features = data.get('features') // Assume the client sends features as a list or dict
if features is None:
return jsonify({'error': 'Features data not provided'}), 400
// Preprocess features if necessary; this may include normalization, tokenization, etc.
processed\_features = features // Replace with actual preprocessing if needed
// Get prediction from model
prediction = model.predict([processed\_features])
return jsonify({'prediction': prediction.tolist()})
// Run the Flask server
if **name** == '**main**':
app.run(debug=True)
// Example of processing steps
def preprocess_input(raw_data):
// Apply necessary transformation like normalization
preprocessed = raw\_data // Replace with actual preprocessing logic
return preprocessed
def postprocess\_output(prediction):
// Format the candidate output properly
formatted\_prediction = prediction // Replace with output formatting logic
return formatted\_prediction
@app.route('/predict', methods=['POST'])
def predict():
data = request.get\_json()
features = data.get('features')
if features is None:
return jsonify({'error': 'Features data not provided'}), 400
input_data = preprocess_input(features)
prediction = model.predict([input\_data])
result = postprocess\_output(prediction)
return jsonify({'prediction': result.tolist()})
// Example: including a version in the API response
CURRENT_MODEL_VERSION = "1.0.0"
@app.route('/predict', methods=['POST'])
def predict():
data = request.get\_json()
features = data.get('features')
if features is None:
return jsonify({'error': 'Features data not provided'}), 400
input_data = preprocess_input(features)
prediction = model.predict([input\_data])
result = postprocess\_output(prediction)
return jsonify({
'model_version': CURRENT_MODEL\_VERSION,
'prediction': result.tolist()
})
// Example using FastAPI with asynchronous capabilities
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
app = FastAPI()
model = joblib.load('path/to/your/model.pkl')
class PredictRequest(BaseModel):
features: list // Validate the incoming JSON structure
@app.post('/predict')
async def predict(request: PredictRequest):
features = request.features
input_data = preprocess_input(features) // Reuse preprocessing function if defined
prediction = model.predict([input\_data])
result = postprocess\_output(prediction)
return {"model_version": CURRENT_MODEL\_VERSION, "prediction": result.tolist()}
// Enhancing our prediction endpoint with error handling and logging
import logging
// Setup basic logging
logging.basicConfig(level=logging.INFO)
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.get\_json()
features = data.get('features')
if features is None:
logging.error("No features provided in the request")
return jsonify({'error': 'Features data not provided'}), 400
input_data = preprocess_input(features)
prediction = model.predict([input\_data])
result = postprocess\_output(prediction)
logging.info("Prediction successful for input: %s", features)
return jsonify({
'model_version': CURRENT_MODEL\_VERSION,
'prediction': result.tolist()
})
except Exception as e:
logging.exception("Prediction failed due to an error")
return jsonify({'error': 'Prediction failed', 'details': str(e)}), 500
// Example Dockerfile for a Flask application
FROM python:3.8-slim
WORKDIR /app
// Copy requirements file and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
// Copy your application code
COPY . .
// Expose the port the app runs on
EXPOSE 5000
// Run the Flask application with Gunicorn for production
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "your\_app:app"]
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â