Flask-CORS: Handling Cross-Origin Requests

Explore practical examples of using Flask-CORS for managing cross-origin requests in your applications.
By Jamie

Introduction to Flask-CORS

Flask-CORS is an extension for Flask that simplifies the process of handling Cross-Origin Resource Sharing (CORS) in web applications. CORS is a security feature implemented by browsers to prevent web pages from making requests to a different domain than the one that served the web page. This is particularly important for APIs that need to be accessed from different origins. By using Flask-CORS, developers can easily control which domains are allowed to make requests to their API endpoints, enhancing both security and functionality.

Example 1: Basic CORS Configuration

Use Case

In this scenario, you have a Flask API that needs to allow requests from a frontend application hosted on a different domain. You want to enable CORS for all routes in your Flask app.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

@app.route('/data')
def data():
    return {'message': 'Hello from Flask!'}

if __name__ == '__main__':
    app.run(debug=True)

Notes

  • This configuration allows all domains to access your API. For production environments, consider restricting access to specific domains for enhanced security.

Example 2: Allowing Specific Origins

Use Case

You have a public API and want to allow requests only from a specific frontend application hosted on https://myfrontend.com. This approach improves security by limiting which domains can access your API.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r'/data': {'origins': 'https://myfrontend.com'}})

@app.route('/data')
def data():
    return {'message': 'Data sent to a specific origin!'}

if __name__ == '__main__':
    app.run(debug=True)

Notes

  • You can specify multiple origins by passing a list to the origins parameter, e.g., origins=['https://myfrontend.com', 'https://anotherdomain.com'].

Example 3: Configuring CORS for Different HTTP Methods

Use Case

In this example, your API needs to allow cross-origin requests for GET and POST methods but deny others, such as DELETE. This is useful for APIs where you want tighter control over which operations can be performed from different origins.

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r'/data': {'origins': '*', 'methods': ['GET', 'POST']}})

@app.route('/data', methods=['GET', 'POST'])
def data():
    if request.method == 'POST':
        return {'message': 'Data received!'}, 201
    return {'message': 'Data sent!'}

if __name__ == '__main__':
    app.run(debug=True)

Notes

  • Ensure that the methods you allow align with your application’s functionality. Always review CORS settings to prevent unintended access.