arundhaj

all that is technology

Definitive guide to solve CORS error, Access-Control-Allow-Origin in Python Flask APIs

 

In this video, I'll show how to enable Flask-CORS for Flask based API projects. Explains and code three different options available to configure CORS for your projects.

Starting with the basic Flask project.

  • Update requirements.txt file to include Flask-CORS and install the requirements
Flask
Flask-CORS

Option 1: Configuring globally

  • Enable CORS globally, with permissive configurations
CORS(app)

curl command to test the configuration

$ curl -v -X OPTIONS 
    http://localhost:5000/hello
  • Configure Access-Control-Allow-Origin option
api_v1_cors_config = {
  "origins": ["http://localhost:5000"]
}
CORS(app, resources={"/api/v1/*": api_v1_cors_config})

curl command to test the configuration

$ curl -v -X OPTIONS 
    -H "Origin: http://localhost:5000" 
    http://localhost:5000/api/v1/hello
  • Configure Access-Control-Allow-Methods option
api_v1_cors_config = {
  ...
  "methods": ["OPTIONS", "GET", "POST"],
}
CORS(app, resources={"/api/v1/*": api_v1_cors_config})

curl command to test the configuration

$ curl -v -X OPTIONS 
    -H "Origin: http://localhost:5000"
    -H "Access-Control-Request-Method: GET"
    http://localhost:5000/api/v1/hello
  • Configure Access-Control-Allow-Headers option
api_v1_cors_config = {
  ...
  "allow_headers": ["Authorization"]
}
CORS(app, resources={"/api/v1/*": api_v1_cors_config})

curl command to test the configuration

$ curl -v -X OPTIONS 
    -H "Origin: http://localhost:5000"
    -H "Access-Control-Request-Method: GET"
    -H "Access-Control-Request-Headers: Authorization"
    http://localhost:5000/api/v1/hello

Option 2: Configuring using Decorator

api_v2_cors_config = {
  "origins": ["http://localhost:5000"],
  "methods": ["OPTIONS", "GET", "POST"],
  "allow_headers": ["Authorization", "Content-Type"]
}

@app.route('/api/v2/hello')
@cross_origin(**api_v2_cors_config)
def v2_hello():
    return 'Hello World v2'

Option 3: Configuring globally for multiple resources

CORS(app, resources={
    r"/api/v1/*": api_v1_cors_config,
    r"/api/v2/*": api_v2_cors_config
})

Hope this helps!

  Python

Comments