arundhaj

all that is technology

How to Configure and Use Flask-CORS

 

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that controls how web pages in one domain can request and interact with resources hosted on another domain. When building a Flask API that will be accessed by a frontend running on a different port or domain, you'll inevitably encounter CORS issues.

In this article, we'll explore how to configure and use the flask-cors extension to handle CORS headers in your Flask application effectively.

What is Flask-CORS?

Flask-CORS is a Flask extension that creates a simple way to enable CORS support in your application. It provides a decorator and configuration options to handle Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible.

Installation

First, you need to install the extension using pip:

pip install flask-cors

Basic Usage

The simplest way to enable CORS for all domains on all clean routes is to initialize it with your Flask app instance.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

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

This configuration allows all origins to access all routes under /, which is simple but arguably too permissive for production environments.

Resource Specific Usage

If you want to restrict CORS to specific routes, you can pass a resources dictionary to the CORS constructor.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# Only allow CORS for paths starting with /api/
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.route("/api/v1/users")
def list_users():
  return "Users list"

@app.route("/")
def home():
  return "Home page"

Route Specific Usage

For more granular control, you can use the @cross_origin() decorator on specific view functions. This is useful when only certain endpoints need to be accessible from other domains.

from flask import Flask
from flask_cors import cross_origin

app = Flask(__name__)

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

@app.route("/api/data")
@cross_origin()
def get_data():
  return "This data is accessible from any origin"

Configuration Options

Flask-CORS offers several configuration options to fine-tune your security settings.

Restricting to Specific Origins

You should restrict access to trusted domains in a production environment.

CORS(app, resources={r"/api/*": {"origins": ["https://example.com", "https://app.example.com"]}})

Allowing Specific Methods and Headers

You can also specify which HTTP methods and headers are allowed.

CORS(app, methods=["GET", "POST"], allow_headers=["Content-Type", "Authorization"])

Handling CORS is a common requirement for modern web applications. Flask-CORS makes it incredibly easy to configure these settings, whether you need a global configuration or fine-grained control over specific resources.

Hope this helps!

Comments