Skip to content

Commit

Permalink
Added CORS to API Gateway
Browse files Browse the repository at this point in the history
  • Loading branch information
John-J-Riehl committed May 17, 2022
1 parent f71bacf commit 2349bba
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
1 change: 1 addition & 0 deletions api-gateway/apis.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{
"api_name": "immortal_memes",
"api_type": "HTTP",
"Access-Control-Allow-Origin": ["*"],
"integrations": {
"0": {"type": "lambda", "region": "us-east-1", "function": "im-health-check"}
},
Expand Down
18 changes: 14 additions & 4 deletions api-gateway/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# Integrations: Lambda
# Methods: any (including the ANY method specifier)
# Path variables: yes, except for greedy variables.
# CORS: Access-Control-Allow-Origin only
#
# For more information on Flask, see
# https://flask.palletsprojects.com/en/2.1.x/. A few notes:
Expand All @@ -28,12 +29,10 @@
# https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

from flask import Flask, request
from flask_cors import CORS
import json, boto3
from botocore.config import Config

# Elastic Beanstalk looks for a callable named application
application = Flask(__name__)

class LambdaInvoker():
"""Represents a callable invoker for an AWS Lambda function.
Expand Down Expand Up @@ -135,7 +134,11 @@ def get_required_entry(dictionary, key, exception_text):

return result

# load the API(s) from a config file
# Start building the app. Elastic Beanstalk looks for a callable named
# application.
application = Flask(__name__)

# load the config file
config = None

try:
Expand All @@ -151,6 +154,8 @@ def get_required_entry(dictionary, key, exception_text):
apis = []

# build the route handlers
cors_origins = []

try:
for api in apis:
api_name = get_required_entry(
Expand Down Expand Up @@ -231,6 +236,8 @@ def get_required_entry(dictionary, key, exception_text):
else:
raise Exception(f"api type {api_type} not implemented")

cors_origins += api.get("Access-Control-Allow-Origin", [])

except Exception as err:
# reset the application and add an error route
application = Flask(__name__)
Expand All @@ -243,4 +250,7 @@ def get_required_entry(dictionary, key, exception_text):

# run the app.
if __name__ == "__main__":
if cors_origins:
CORS(application, origins=cors_origins)

application.run()
1 change: 1 addition & 0 deletions api-gateway/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ botocore==1.24.43
click==8.1.2
colorama==0.4.4
Flask==2.1.1
Flask-Cors==3.0.10
importlib-metadata==4.11.3
itsdangerous==2.1.2
Jinja2==3.1.1
Expand Down

0 comments on commit 2349bba

Please sign in to comment.