Solve CORS problem in Flask REST API

Privalov Vladimir
1 min readApr 16, 2021

--

Cross-domain requests are not allowed on default due to security reasons. If client from another domain and/or port that the server located at will send any request to REST API server browser will block it.

CORS request should be enabled on server. To allow client send CORS requests to our backend we need to add special headers “Access-Control-Allow-Origin” to server response. This header saying browser that the server accepts CORS requests from specified origins (source of request). Value “*” means that the server accepts CORS requests from all origins.

For Flask REST API framework we can use library Flask-CORS.

Install Flask-CORS

pip install -U flask-cors

Add following lines in app/__init__.py:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"

Add cross_origin decorator

from flask_cors import cross_origin@analytics_blueprint.route('/analytics', methods=['GET'])
@cross_origin()
def index():
return jsonify(mock)

That’s it. Now it should work for all routes decorated by cross_origin.

--

--

Responses (1)