CORS in Flask API: 3 Practical Examples

Learn how to implement CORS in your Flask API with these three practical examples.
By Taylor

Understanding CORS in Flask APIs

Cross-Origin Resource Sharing (CORS) is a crucial security feature that allows or restricts resources requested from another domain outside the domain from which the first resource was served. When developing APIs, especially when the frontend and backend are hosted on different domains, you’ll need to set up CORS to enable your application to communicate without issues. In this article, we’ll explore three practical examples of setting up CORS in a Flask API.

Example 1: Enabling CORS for All Origins

Context:

In many cases, you may want to allow requests from any origin. This is common during development or if your API is intended to be public.

Implementation:

To set up CORS for all origins in a Flask API, you can use the flask-cors library, which simplifies the process significantly.

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # This allows all origins by default

@app.route('/api/data', methods=['GET'])
def get_data():
    return jsonify({'message': 'This is data from your API!'})

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

Notes:

  • This setup is excellent for development, but be cautious in production, as it opens your API to any origin.
  • You can specify certain routes if you don’t want to enable CORS globally.

Example 2: Allowing Specific Origins

Context:

You might want more control over who can access your API. For example, if you have a web application hosted on a specific domain, you can restrict CORS to that domain only.

Implementation:

Using the flask-cors library, you can specify which origins are allowed access to your API.

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r'/api/*': {'origins': 'https://example.com'}})

@app.route('/api/data', methods=['GET'])
def get_data():
    return jsonify({'message': 'This data is accessible from example.com!'})

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

Notes:

  • Replace https://example.com with your actual domain.
  • You can add a list of domains if needed, like origins=['https://example.com', 'https://another-domain.com'].

Example 3: Allowing Credentials with CORS

Context:

Sometimes, you may need to allow credentials such as cookies or HTTP authentication to be included in the requests. This requires a slightly different setup in CORS.

Implementation:

With the flask-cors library, you can specify that credentials are allowed by setting supports_credentials=True.

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app, supports_credentials=True, resources={r'/api/*': {'origins': 'https://example.com'}})

@app.route('/api/data', methods=['GET'])
def get_data():
    return jsonify({'message': 'This data requires credentials!'})

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

Notes:

  • Ensure your frontend application is set to send credentials with requests, as this won’t work if the frontend is not configured correctly.
  • Be cautious about exposing sensitive data when using credentials with CORS.

These examples of setting up CORS in a Flask API should help you understand how to manage cross-origin requests effectively. Whether you’re allowing all origins, specific domains, or credentials, you can easily adapt your API to suit your needs.