/web-to-ai-ml-integrations

Create REST API for ML Model

Step-by-step guide to build a REST API for your ML model. Discover coding, integration, and deployment tips for smooth operations.

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Create REST API for ML Model

Introduction  

 
  • Goal: Integrate an existing Machine Learning (ML) model into a REST API to expose the model for external use.
  • Overview: In this guide, you will define and save your ML model, build a REST API using a lightweight framework, load the model inside the API, and create a prediction endpoint to serve the model's outputs.

Define and Save Your ML Model  

 
  • Description: Train your ML model using your preferred ML library (for example, scikit-learn, TensorFlow, PyTorch, etc.) and save the trained model. Saving the model allows you to load it quickly when the API starts, avoiding retraining during each request.
  • Example: Here, we use a simple scikit-learn model and save it using the joblib library.

// Import necessary libraries for modeling and saving
import joblib          
from sklearn.datasets import load\_iris  
from sklearn.linear\_model import LogisticRegression

// Load dataset and train a basic logistic regression model
data = load\_iris()
X, y = data.data, data.target
model = LogisticRegression(max\_iter=200)
model.fit(X, y)

// Save the trained model to disk
joblib.dump(model, 'model.pkl')    // Saves model to the file 'model.pkl'

Set Up a REST API Server Using Flask  

 
  • Description: Use Flask, a lightweight web framework, to implement a REST API. Flask is simple yet powerful, making it ideal for creating quick endpoints that communicate with your ML model.
  • Initialization: Create an application file that imports Flask and configures the main application.

// Import Flask for building the REST API
from flask import Flask, request, jsonify
import joblib

// Initialize the Flask application
app = Flask(**name**)

// Load the pre-saved ML model during startup for efficiency
model = joblib.load('model.pkl')

Create a Prediction Endpoint  

 
  • Description: Develop an API endpoint that receives prediction requests. The endpoint should extract input features from the request, process them with the loaded model, and return predictions in JSON format.
  • Key Points:
    • Input validation: Ensure the incoming feature data is in the expected format.
    • Error handling: Return friendly error messages if the data or request is malformed.

// Define a route '/predict' that listens to POST requests
@app.route('/predict', methods=['POST'])
def predict():
    // Extract JSON data from POST request
    data = request.get\_json(force=True)
    
    // Validate presence of 'features' key in data
    if 'features' not in data:
        return jsonify({'error': 'No features provided in request'}), 400
    
    try:
        // Convert features into proper data structure for the model, e.g., list to array
        features = data['features']
        // Generate prediction using the loaded model
        prediction = model.predict([features])
        
        // Return the prediction as a JSON object
        return jsonify({'prediction': prediction[0]})
    except Exception as e:
        // In case of an error, return an error response with the exception message
        return jsonify({'error': str(e)}), 500

// Run the Flask app (development mode) when this script is executed
if **name** == '**main**':
    app.run(debug=True)

Testing the REST API Endpoint  

 
  • Description: Test your API endpoint and ensure that correct predictions are returned. Use HTTP clients such as curl or Postman to test the endpoint.
  • Example Request:
    • Using curl: Send a POST request containing feature data in JSON.

// Example of sending a test request using curl
// Command to execute in your terminal
// curl -X POST -H "Content-Type: application/json" -d '{"features": [5.1, 3.5, 1.4, 0.2]}' http://127.0.0.1:5000/predict

Considerations for Production Deployment  

 
  • Description: While Flask's built-in server is sufficient for development, you may need a production-level WSGI server like Gunicorn or uWSGI when deploying your application to handle real-world traffic.
  • Security: Always perform proper input sanitization and deploy secure configurations when exposing an API publicly.
  • Scalability: Consider containerization or cloud-based solutions for scaling beyond single-instance deployments.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

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.Â