0
0
Flaskframework~30 mins

CORS configuration with Flask-CORS - Mini Project: Build & Apply

Choose your learning style9 modes available
CORS configuration with Flask-CORS
📖 Scenario: You are building a simple Flask web API that will be accessed by a frontend running on a different domain. To allow this cross-origin access safely, you need to configure CORS (Cross-Origin Resource Sharing) properly.
🎯 Goal: Set up a Flask app with Flask-CORS to allow cross-origin requests only from http://example.com. You will create the app, configure CORS, and add a simple route that returns JSON data.
📋 What You'll Learn
Create a Flask app instance named app
Import and use CORS from flask_cors
Configure CORS to allow only http://example.com as an origin
Add a route /data that returns JSON {"message": "Hello from Flask"}
💡 Why This Matters
🌍 Real World
Many web APIs need to allow frontend apps hosted on different domains to access their data safely. Configuring CORS correctly prevents security issues and enables smooth communication.
💼 Career
Backend developers often configure CORS in Flask or other frameworks to ensure their APIs are accessible only to trusted clients, which is a common task in web development jobs.
Progress0 / 4 steps
1
Create the Flask app instance
Import Flask from flask and create a Flask app instance called app.
Flask
Need a hint?

Use Flask(__name__) to create the app instance.

2
Import and configure Flask-CORS
Import CORS from flask_cors and configure it on the app to allow only http://example.com as an origin.
Flask
Need a hint?

Use CORS(app, origins=["http://example.com"]) to restrict access.

3
Add a route that returns JSON data
Add a route /data to the app that returns a JSON response with {"message": "Hello from Flask"}. Use @app.route and a function named data.
Flask
Need a hint?

Use jsonify to return JSON data from the route.

4
Add the app run command
Add the code to run the Flask app only if the script is executed directly. Use if __name__ == '__main__': and run app.run().
Flask
Need a hint?

This code ensures the app runs only when you execute this script directly.