Step-by-step guide to handle CORS for your Flask ML API. Master cross-origin requests with clear, efficient tips for robust API security.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
When you deploy a Machine Learning API built with Flask, it is common for the frontend application (or even other services) to be hosted on a different domain or port. This leads to cross-origin requests which, by default, are blocked by modern browsers due to security policies. CORS (Cross-Origin Resource Sharing) is a mechanism that allows your API to indicate trusted origins and enable resource sharing across different domains. For ML APIs this is particularly important since you may have separate services for model inference, data visualization, or dashboards that interact with your API.
The easiest and most straightforward way to handle CORS in Flask is by using the Flask-CORS extension. This library automatically handles the CORS headers so that you do not have to manually configure them on every response.
Access-Control-Allow-Origin so that browsers acknowledge the API as a safe cross-domain resource.Below is an example demonstrating how to integrate Flask-CORS into your ML API:
// Import necessary modules
from flask import Flask, request, jsonify
from flask\_cors import CORS // Import Flask-CORS extension
// Create the Flask application instance
app = Flask(**name**)
// Enable CORS for all routes in the application
CORS(app)
// Define a sample ML inference endpoint
@app.route("/predict", methods=["POST"])
def predict():
// Extracting data from the incoming JSON request
data = request.get\_json()
// Example processing: typically, you would integrate your ML model here
// For demonstration, simply echo back the input data
result = {"prediction": "This is a dummy prediction", "input": data}
// Return the result as a JSON response
return jsonify(result)
// Start the Flask application when executed
if **name** == "**main**":
app.run(debug=True)
In this code snippet, the CORS(app) call configures the app to allow cross-origin requests from any domain. This is ideal during development and testing.
For production environments, it is a best practice to restrict CORS to specific origins instead of allowing access from everywhere. The Flask-CORS extension supports detailed configuration.
The following example demonstrates how to configure Flask-CORS with options:
// Import modules
from flask import Flask, request, jsonify
from flask\_cors import CORS
app = Flask(**name**)
// Configure CORS: only allow requests from a specific domain
cors = CORS(app, resources={
r"/predict": {
"origins": ["https://trusted.domain.com"],
"methods": ["POST"],
"allow\_headers": ["Content-Type", "Authorization"],
"supports\_credentials": True // Include credentials such as cookies if needed
}
})
// Define the ML inference endpoint
@app.route("/predict", methods=["POST"])
def predict():
data = request.get\_json()
result = {"prediction": "Processed prediction", "input": data}
return jsonify(result)
if **name** == "**main**":
app.run(debug=True)
This configuration restricts the /predict endpoint so that only requests from https://trusted.domain.com are allowed. You can adjust these options based on your security requirements.
While Flask-CORS is highly recommended for its simplicity, there might be cases when you need more control over the response headers. In such scenarios, you can manually add CORS headers in your endpoints or use Flask’s hooks.
Here’s how you can add CORS headers manually:
// Import necessary modules
from flask import Flask, request, jsonify, make\_response
app = Flask(**name**)
// Define a helper function to add CORS headers
def add_cors_headers(response):
response.headers["Access-Control-Allow-Origin"] = "https://trusted.domain.com"
response.headers["Access-Control-Allow-Methods"] = "POST, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
return response
// Define an endpoint with manual CORS handling
@app.route("/predict", methods=["POST", "OPTIONS"])
def predict():
// If this is a preflight OPTIONS request, directly return the response with headers
if request.method == "OPTIONS":
response = make\_response()
return add_cors_headers(response)
data = request.get\_json()
result = {"prediction": "Manually handled prediction", "input": data}
response = jsonify(result)
// Manually add CORS headers to the response
return add_cors_headers(response)
if **name** == "**main**":
app.run(debug=True)
This manual method gives you complete control over how CORS is managed in your API. However, for most use cases with a straightforward configuration, Flask-CORS remains the preferred solution.
After setting up CORS, it is important to test that your ML API correctly responds to cross-origin requests. You can achieve this by:
This validation phase ensures that your ML API integrated with Flask provides a secure and interoperable interface for clients across different domains.
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.Â