Step-by-step guide to create a custom ML API with Flask Blueprint. Build and deploy smart ML endpoints seamlessly.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
This guide explains how to build a custom machine learning (ML) API using Flask and Flask Blueprints. A Flask Blueprint is a way to organize your Flask application by grouping related routes and logic into separate modules. This separation enhances maintainability and scalability. In this guide, we will create an ML endpoint that loads a pre-trained model, accepts data in JSON format, makes predictions, and returns the results in JSON.
Let's start by setting up a Flask Blueprint dedicated to the ML API. This blueprint will contain the routes responsible for handling prediction requests.
ml\_blueprint.py that initializes the blueprint and sets up its routes.
// ml\_blueprint.py
from flask import Blueprint, request, jsonify
// Initialize the blueprint named "ml_api"
ml_api = Blueprint('ml_api', name)
// Simulated ML model function
def dummy_model_predict(data):
// For each input data, return the length as a sample prediction
return [len(str(item)) for item in data]
// Define the prediction route using POST method
@ml_api.route('/predict', methods=['POST'])
def predict():
try:
// Parse JSON from the incoming request
input_json = request.get_json()
// Validate that the "data" key is present in the JSON payload
if 'data' not in input\_json:
return jsonify({'error': 'Missing parameter: data'}), 400
// Extract data for prediction
data = input\_json['data']
// Make prediction using the dummy model function
prediction = dummy_model_predict(data)
// Return the prediction as JSON
return jsonify({'prediction': prediction}), 200
except Exception as e:
// In case of error, return the error message
return jsonify({'error': str(e)}), 500
This code defines a Blueprint called "ml\_api" with a single route /predict that accepts POST requests containing JSON formatted input. The dummy model simply returns the length of each input item. Error handling is also included.
Once the blueprint is defined, the next step is to register it with the main Flask application. This registration connects the blueprint routes to the main app, allowing them to be accessed as part of your API.
app.py, import Flask and the blueprint, then register the blueprint with a URL prefix (e.g., /ml).
// app.py
from flask import Flask
from ml_blueprint import ml_api // Import the blueprint from the file
// Instantiate the Flask application
app = Flask(name)
// Register the blueprint with a URL prefix, e.g., '/ml'
app.register_blueprint(ml_api, url_prefix='/ml')
// Run the application
if name == 'main':
// Enable debug mode for development
app.run(debug=True)
With the blueprint registered, the prediction endpoint is now accessible at /ml/predict.
This API endpoint works as follows:
This design ensures that the API is robust and provides clear feedback to the client on data issues.
To verify that everything works properly, you can test the API using tools such as Postman or curl. Here is an example using curl:
// Command to test the prediction endpoint
curl -X POST http://localhost:5000/ml/predict -H "Content-Type: application/json" -d '{"data": ["sample", "test"]}'
// Expected response:
// {
// "prediction": [6, 4]
// }
This command sends a POST request containing a JSON payload. The API processes the data and returns an array where each element represents the "prediction" of the corresponding input.
This guide provided a comprehensive walkthrough for creating a custom ML API with Flask Blueprints. We covered how to define a blueprint, create an endpoint for ML predictions, register the blueprint with the main Flask application, and test the endpoint. By following this approach, you modularize your application, making it more maintainable and scalable. Additionally, key technical details such as error handling, data parsing, and response formatting were explained to ensure your API is robust and user-friendly.
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.Â