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.
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.
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)
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.
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)
https://example.com
with your actual domain.origins=['https://example.com', 'https://another-domain.com']
.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.
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)
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.