We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
APIGateway AWS_PROXY integration failing for paths without parameters
I'm trying to run an AWS_PROXY integration between APIGateway and Lambda, and I'm hitting what looks like a fundamental logic bug in the APIGateway implementation.

https://github.com/localstack/localstack/blob/master/localstack/services/apigateway/apigateway_listener.py#L101

```
 File "/opt/code/localstack/localstack/services/apigateway/apigateway_listener.py", line 101, in forward_request
    'resourceId': resource.get('id'),
UnboundLocalError: local variable 'resource' referenced before assignment
```

Scanning up the file, it looks like `resource` is only be initialized within a `catch` block.  I assume this is a simple oversight rather than a complex bug.

This looks like a bug I can fix, but I'd appreciate any guidance you can offer.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `localstack/services/apigateway/apigateway_listener.py`
Content:
```
1 import re
2 import logging
3 import json
4 import requests
5 
6 from requests.models import Response
7 from flask import Response as FlaskResponse
8 from localstack.constants import APPLICATION_JSON, PATH_USER_REQUEST
9 from localstack.config import TEST_KINESIS_URL
10 from localstack.utils import common
11 from localstack.utils.aws import aws_stack
12 from localstack.utils.common import to_str
13 from localstack.services.awslambda import lambda_api
14 from localstack.services.kinesis import kinesis_listener
15 from localstack.services.generic_proxy import ProxyListener
16 from .helpers import (get_rest_api_paths, get_resource_for_path,
17                       flask_to_requests_response, handle_authorizers,
18                       extract_query_string_params, extract_path_params,
19                       make_error, get_cors_response)
20 
21 # set up logger
22 LOGGER = logging.getLogger(__name__)
23 
24 # regex path patterns
25 PATH_REGEX_AUTHORIZERS = r'^/restapis/([A-Za-z0-9_\-]+)/authorizers(\?.*)?'
26 
27 
28 class ProxyListenerApiGateway(ProxyListener):
29 
30     def forward_request(self, method, path, data, headers):
31         data = data and json.loads(to_str(data))
32 
33         # Paths to match
34         regex2 = r'^/restapis/([A-Za-z0-9_\-]+)/([A-Za-z0-9_\-]+)/%s/(.*)$' % PATH_USER_REQUEST
35 
36         if re.match(regex2, path):
37             search_match = re.search(regex2, path)
38             api_id = search_match.group(1)
39             stage = search_match.group(2)
40             relative_path = '/%s' % search_match.group(3)
41             try:
42                 integration = aws_stack.get_apigateway_integration(api_id, method, path=relative_path)
43                 assert integration
44             except Exception:
45                 try:
46                     integration = aws_stack.get_apigateway_integration(api_id, 'ANY', path=relative_path)
47                     assert integration
48                 except Exception:
49                     # if we have no exact match, try to find an API resource that contains path parameters
50                     path_map = get_rest_api_paths(rest_api_id=api_id)
51                     try:
52                         extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)
53                     except Exception:
54                         return make_error('Unable to find path %s' % path, 404)
55 
56                     integrations = resource.get('resourceMethods', {})
57                     integration = integrations.get(method, {})
58                     if not integration:
59                         integration = integrations.get('ANY', {})
60                     integration = integration.get('methodIntegration')
61                     if not integration:
62 
63                         if method == 'OPTIONS' and 'Origin' in headers:
64                             # default to returning CORS headers if this is an OPTIONS request
65                             return get_cors_response(headers)
66 
67                         return make_error('Unable to find integration for path %s' % path, 404)
68 
69             uri = integration.get('uri')
70             if method == 'POST' and integration['type'] == 'AWS':
71                 if uri.endswith('kinesis:action/PutRecords'):
72                     template = integration['requestTemplates'][APPLICATION_JSON]
73                     new_request = aws_stack.render_velocity_template(template, data)
74 
75                     # forward records to target kinesis stream
76                     headers = aws_stack.mock_aws_request_headers(service='kinesis')
77                     headers['X-Amz-Target'] = kinesis_listener.ACTION_PUT_RECORDS
78                     result = common.make_http_request(url=TEST_KINESIS_URL,
79                         method='POST', data=new_request, headers=headers)
80                     return result
81                 else:
82                     msg = 'API Gateway action uri "%s" not yet implemented' % uri
83                     LOGGER.warning(msg)
84                     return make_error(msg, 404)
85 
86             elif integration['type'] == 'AWS_PROXY':
87                 if uri.startswith('arn:aws:apigateway:') and ':lambda:path' in uri:
88                     func_arn = uri.split(':lambda:path')[1].split('functions/')[1].split('/invocations')[0]
89                     account_id = uri.split(':lambda:path')[1].split(':function:')[0].split(':')[-1]
90                     data_str = json.dumps(data) if isinstance(data, dict) else data
91 
92                     relative_path, query_string_params = extract_query_string_params(path=relative_path)
93 
94                     source_ip = headers['X-Forwarded-For'].split(',')[-2]
95 
96                     # Sample request context:
97                     # https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-create-api-as-simple-proxy-for-lambda-test
98                     request_context = {
99                         'path': relative_path,
100                         'accountId': account_id,
101                         'resourceId': resource.get('id'),
102                         'stage': stage,
103                         'identity': {
104                             'accountId': account_id,
105                             'sourceIp': source_ip,
106                             'userAgent': headers['User-Agent'],
107                         }
108                     }
109 
110                     try:
111                         path_params = extract_path_params(path=relative_path, extracted_path=extracted_path)
112                     except Exception:
113                         path_params = {}
114 
115                     result = lambda_api.process_apigateway_invocation(func_arn, relative_path, data_str,
116                         headers, path_params=path_params, query_string_params=query_string_params,
117                         method=method, resource_path=path, request_context=request_context)
118 
119                     if isinstance(result, FlaskResponse):
120                         return flask_to_requests_response(result)
121 
122                     response = Response()
123                     parsed_result = result if isinstance(result, dict) else json.loads(result)
124                     parsed_result = common.json_safe(parsed_result)
125                     response.status_code = int(parsed_result.get('statusCode', 200))
126                     response.headers.update(parsed_result.get('headers', {}))
127                     try:
128                         if isinstance(parsed_result['body'], dict):
129                             response._content = json.dumps(parsed_result['body'])
130                         else:
131                             response._content = parsed_result['body']
132                     except Exception:
133                         response._content = '{}'
134                     return response
135                 else:
136                     msg = 'API Gateway action uri "%s" not yet implemented' % uri
137                     LOGGER.warning(msg)
138                     return make_error(msg, 404)
139 
140             elif integration['type'] == 'HTTP':
141                 function = getattr(requests, method.lower())
142                 if isinstance(data, dict):
143                     data = json.dumps(data)
144                 result = function(integration['uri'], data=data, headers=headers)
145                 return result
146 
147             else:
148                 msg = ('API Gateway integration type "%s" for method "%s" not yet implemented' %
149                        (integration['type'], method))
150                 LOGGER.warning(msg)
151                 return make_error(msg, 404)
152 
153             return 200
154 
155         if re.match(PATH_REGEX_AUTHORIZERS, path):
156             return handle_authorizers(method, path, data, headers)
157 
158         return True
159 
160 
161 # instantiate listener
162 UPDATE_APIGATEWAY = ProxyListenerApiGateway()
163
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/localstack/services/apigateway/apigateway_listener.py b/localstack/services/apigateway/apigateway_listener.py
--- a/localstack/services/apigateway/apigateway_listener.py
+++ b/localstack/services/apigateway/apigateway_listener.py
@@ -37,34 +37,28 @@
             search_match = re.search(regex2, path)
             api_id = search_match.group(1)
             stage = search_match.group(2)
-            relative_path = '/%s' % search_match.group(3)
+            relative_path_w_query_params = '/%s' % search_match.group(3)
+
+            relative_path, query_string_params = extract_query_string_params(path=relative_path_w_query_params)
+
+            path_map = get_rest_api_paths(rest_api_id=api_id)
             try:
-                integration = aws_stack.get_apigateway_integration(api_id, method, path=relative_path)
-                assert integration
+                extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)
             except Exception:
-                try:
-                    integration = aws_stack.get_apigateway_integration(api_id, 'ANY', path=relative_path)
-                    assert integration
-                except Exception:
-                    # if we have no exact match, try to find an API resource that contains path parameters
-                    path_map = get_rest_api_paths(rest_api_id=api_id)
-                    try:
-                        extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)
-                    except Exception:
-                        return make_error('Unable to find path %s' % path, 404)
+                return make_error('Unable to find path %s' % path, 404)
 
-                    integrations = resource.get('resourceMethods', {})
-                    integration = integrations.get(method, {})
-                    if not integration:
-                        integration = integrations.get('ANY', {})
-                    integration = integration.get('methodIntegration')
-                    if not integration:
+            integrations = resource.get('resourceMethods', {})
+            integration = integrations.get(method, {})
+            if not integration:
+                integration = integrations.get('ANY', {})
+            integration = integration.get('methodIntegration')
+            if not integration:
 
-                        if method == 'OPTIONS' and 'Origin' in headers:
-                            # default to returning CORS headers if this is an OPTIONS request
-                            return get_cors_response(headers)
+                if method == 'OPTIONS' and 'Origin' in headers:
+                    # default to returning CORS headers if this is an OPTIONS request
+                    return get_cors_response(headers)
 
-                        return make_error('Unable to find integration for path %s' % path, 404)
+                return make_error('Unable to find integration for path %s' % path, 404)
 
             uri = integration.get('uri')
             if method == 'POST' and integration['type'] == 'AWS':
@@ -89,8 +83,6 @@
                     account_id = uri.split(':lambda:path')[1].split(':function:')[0].split(':')[-1]
                     data_str = json.dumps(data) if isinstance(data, dict) else data
 
-                    relative_path, query_string_params = extract_query_string_params(path=relative_path)
-
                     source_ip = headers['X-Forwarded-For'].split(',')[-2]
 
                     # Sample request context:

{"golden_diff": "diff --git a/localstack/services/apigateway/apigateway_listener.py b/localstack/services/apigateway/apigateway_listener.py\n--- a/localstack/services/apigateway/apigateway_listener.py\n+++ b/localstack/services/apigateway/apigateway_listener.py\n@@ -37,34 +37,28 @@\n             search_match = re.search(regex2, path)\n             api_id = search_match.group(1)\n             stage = search_match.group(2)\n-            relative_path = '/%s' % search_match.group(3)\n+            relative_path_w_query_params = '/%s' % search_match.group(3)\n+\n+            relative_path, query_string_params = extract_query_string_params(path=relative_path_w_query_params)\n+\n+            path_map = get_rest_api_paths(rest_api_id=api_id)\n             try:\n-                integration = aws_stack.get_apigateway_integration(api_id, method, path=relative_path)\n-                assert integration\n+                extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)\n             except Exception:\n-                try:\n-                    integration = aws_stack.get_apigateway_integration(api_id, 'ANY', path=relative_path)\n-                    assert integration\n-                except Exception:\n-                    # if we have no exact match, try to find an API resource that contains path parameters\n-                    path_map = get_rest_api_paths(rest_api_id=api_id)\n-                    try:\n-                        extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)\n-                    except Exception:\n-                        return make_error('Unable to find path %s' % path, 404)\n+                return make_error('Unable to find path %s' % path, 404)\n \n-                    integrations = resource.get('resourceMethods', {})\n-                    integration = integrations.get(method, {})\n-                    if not integration:\n-                        integration = integrations.get('ANY', {})\n-                    integration = integration.get('methodIntegration')\n-                    if not integration:\n+            integrations = resource.get('resourceMethods', {})\n+            integration = integrations.get(method, {})\n+            if not integration:\n+                integration = integrations.get('ANY', {})\n+            integration = integration.get('methodIntegration')\n+            if not integration:\n \n-                        if method == 'OPTIONS' and 'Origin' in headers:\n-                            # default to returning CORS headers if this is an OPTIONS request\n-                            return get_cors_response(headers)\n+                if method == 'OPTIONS' and 'Origin' in headers:\n+                    # default to returning CORS headers if this is an OPTIONS request\n+                    return get_cors_response(headers)\n \n-                        return make_error('Unable to find integration for path %s' % path, 404)\n+                return make_error('Unable to find integration for path %s' % path, 404)\n \n             uri = integration.get('uri')\n             if method == 'POST' and integration['type'] == 'AWS':\n@@ -89,8 +83,6 @@\n                     account_id = uri.split(':lambda:path')[1].split(':function:')[0].split(':')[-1]\n                     data_str = json.dumps(data) if isinstance(data, dict) else data\n \n-                    relative_path, query_string_params = extract_query_string_params(path=relative_path)\n-\n                     source_ip = headers['X-Forwarded-For'].split(',')[-2]\n \n                     # Sample request context:\n", "issue": "APIGateway AWS_PROXY integration failing for paths without parameters\nI'm trying to run an AWS_PROXY integration between APIGateway and Lambda, and I'm hitting what looks like a fundamental logic bug in the APIGateway implementation.\r\n\r\nhttps://github.com/localstack/localstack/blob/master/localstack/services/apigateway/apigateway_listener.py#L101\r\n\r\n```\r\n File \"/opt/code/localstack/localstack/services/apigateway/apigateway_listener.py\", line 101, in forward_request\r\n    'resourceId': resource.get('id'),\r\nUnboundLocalError: local variable 'resource' referenced before assignment\r\n```\r\n\r\nScanning up the file, it looks like `resource` is only be initialized within a `catch` block.  I assume this is a simple oversight rather than a complex bug.\r\n\r\nThis looks like a bug I can fix, but I'd appreciate any guidance you can offer.\n", "before_files": [{"content": "import re\nimport logging\nimport json\nimport requests\n\nfrom requests.models import Response\nfrom flask import Response as FlaskResponse\nfrom localstack.constants import APPLICATION_JSON, PATH_USER_REQUEST\nfrom localstack.config import TEST_KINESIS_URL\nfrom localstack.utils import common\nfrom localstack.utils.aws import aws_stack\nfrom localstack.utils.common import to_str\nfrom localstack.services.awslambda import lambda_api\nfrom localstack.services.kinesis import kinesis_listener\nfrom localstack.services.generic_proxy import ProxyListener\nfrom .helpers import (get_rest_api_paths, get_resource_for_path,\n                      flask_to_requests_response, handle_authorizers,\n                      extract_query_string_params, extract_path_params,\n                      make_error, get_cors_response)\n\n# set up logger\nLOGGER = logging.getLogger(__name__)\n\n# regex path patterns\nPATH_REGEX_AUTHORIZERS = r'^/restapis/([A-Za-z0-9_\\-]+)/authorizers(\\?.*)?'\n\n\nclass ProxyListenerApiGateway(ProxyListener):\n\n    def forward_request(self, method, path, data, headers):\n        data = data and json.loads(to_str(data))\n\n        # Paths to match\n        regex2 = r'^/restapis/([A-Za-z0-9_\\-]+)/([A-Za-z0-9_\\-]+)/%s/(.*)$' % PATH_USER_REQUEST\n\n        if re.match(regex2, path):\n            search_match = re.search(regex2, path)\n            api_id = search_match.group(1)\n            stage = search_match.group(2)\n            relative_path = '/%s' % search_match.group(3)\n            try:\n                integration = aws_stack.get_apigateway_integration(api_id, method, path=relative_path)\n                assert integration\n            except Exception:\n                try:\n                    integration = aws_stack.get_apigateway_integration(api_id, 'ANY', path=relative_path)\n                    assert integration\n                except Exception:\n                    # if we have no exact match, try to find an API resource that contains path parameters\n                    path_map = get_rest_api_paths(rest_api_id=api_id)\n                    try:\n                        extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)\n                    except Exception:\n                        return make_error('Unable to find path %s' % path, 404)\n\n                    integrations = resource.get('resourceMethods', {})\n                    integration = integrations.get(method, {})\n                    if not integration:\n                        integration = integrations.get('ANY', {})\n                    integration = integration.get('methodIntegration')\n                    if not integration:\n\n                        if method == 'OPTIONS' and 'Origin' in headers:\n                            # default to returning CORS headers if this is an OPTIONS request\n                            return get_cors_response(headers)\n\n                        return make_error('Unable to find integration for path %s' % path, 404)\n\n            uri = integration.get('uri')\n            if method == 'POST' and integration['type'] == 'AWS':\n                if uri.endswith('kinesis:action/PutRecords'):\n                    template = integration['requestTemplates'][APPLICATION_JSON]\n                    new_request = aws_stack.render_velocity_template(template, data)\n\n                    # forward records to target kinesis stream\n                    headers = aws_stack.mock_aws_request_headers(service='kinesis')\n                    headers['X-Amz-Target'] = kinesis_listener.ACTION_PUT_RECORDS\n                    result = common.make_http_request(url=TEST_KINESIS_URL,\n                        method='POST', data=new_request, headers=headers)\n                    return result\n                else:\n                    msg = 'API Gateway action uri \"%s\" not yet implemented' % uri\n                    LOGGER.warning(msg)\n                    return make_error(msg, 404)\n\n            elif integration['type'] == 'AWS_PROXY':\n                if uri.startswith('arn:aws:apigateway:') and ':lambda:path' in uri:\n                    func_arn = uri.split(':lambda:path')[1].split('functions/')[1].split('/invocations')[0]\n                    account_id = uri.split(':lambda:path')[1].split(':function:')[0].split(':')[-1]\n                    data_str = json.dumps(data) if isinstance(data, dict) else data\n\n                    relative_path, query_string_params = extract_query_string_params(path=relative_path)\n\n                    source_ip = headers['X-Forwarded-For'].split(',')[-2]\n\n                    # Sample request context:\n                    # https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-create-api-as-simple-proxy-for-lambda-test\n                    request_context = {\n                        'path': relative_path,\n                        'accountId': account_id,\n                        'resourceId': resource.get('id'),\n                        'stage': stage,\n                        'identity': {\n                            'accountId': account_id,\n                            'sourceIp': source_ip,\n                            'userAgent': headers['User-Agent'],\n                        }\n                    }\n\n                    try:\n                        path_params = extract_path_params(path=relative_path, extracted_path=extracted_path)\n                    except Exception:\n                        path_params = {}\n\n                    result = lambda_api.process_apigateway_invocation(func_arn, relative_path, data_str,\n                        headers, path_params=path_params, query_string_params=query_string_params,\n                        method=method, resource_path=path, request_context=request_context)\n\n                    if isinstance(result, FlaskResponse):\n                        return flask_to_requests_response(result)\n\n                    response = Response()\n                    parsed_result = result if isinstance(result, dict) else json.loads(result)\n                    parsed_result = common.json_safe(parsed_result)\n                    response.status_code = int(parsed_result.get('statusCode', 200))\n                    response.headers.update(parsed_result.get('headers', {}))\n                    try:\n                        if isinstance(parsed_result['body'], dict):\n                            response._content = json.dumps(parsed_result['body'])\n                        else:\n                            response._content = parsed_result['body']\n                    except Exception:\n                        response._content = '{}'\n                    return response\n                else:\n                    msg = 'API Gateway action uri \"%s\" not yet implemented' % uri\n                    LOGGER.warning(msg)\n                    return make_error(msg, 404)\n\n            elif integration['type'] == 'HTTP':\n                function = getattr(requests, method.lower())\n                if isinstance(data, dict):\n                    data = json.dumps(data)\n                result = function(integration['uri'], data=data, headers=headers)\n                return result\n\n            else:\n                msg = ('API Gateway integration type \"%s\" for method \"%s\" not yet implemented' %\n                       (integration['type'], method))\n                LOGGER.warning(msg)\n                return make_error(msg, 404)\n\n            return 200\n\n        if re.match(PATH_REGEX_AUTHORIZERS, path):\n            return handle_authorizers(method, path, data, headers)\n\n        return True\n\n\n# instantiate listener\nUPDATE_APIGATEWAY = ProxyListenerApiGateway()\n", "path": "localstack/services/apigateway/apigateway_listener.py"}], "after_files": [{"content": "import re\nimport logging\nimport json\nimport requests\n\nfrom requests.models import Response\nfrom flask import Response as FlaskResponse\nfrom localstack.constants import APPLICATION_JSON, PATH_USER_REQUEST\nfrom localstack.config import TEST_KINESIS_URL\nfrom localstack.utils import common\nfrom localstack.utils.aws import aws_stack\nfrom localstack.utils.common import to_str\nfrom localstack.services.awslambda import lambda_api\nfrom localstack.services.kinesis import kinesis_listener\nfrom localstack.services.generic_proxy import ProxyListener\nfrom .helpers import (get_rest_api_paths, get_resource_for_path,\n                      flask_to_requests_response, handle_authorizers,\n                      extract_query_string_params, extract_path_params,\n                      make_error, get_cors_response)\n\n# set up logger\nLOGGER = logging.getLogger(__name__)\n\n# regex path patterns\nPATH_REGEX_AUTHORIZERS = r'^/restapis/([A-Za-z0-9_\\-]+)/authorizers(\\?.*)?'\n\n\nclass ProxyListenerApiGateway(ProxyListener):\n\n    def forward_request(self, method, path, data, headers):\n        data = data and json.loads(to_str(data))\n\n        # Paths to match\n        regex2 = r'^/restapis/([A-Za-z0-9_\\-]+)/([A-Za-z0-9_\\-]+)/%s/(.*)$' % PATH_USER_REQUEST\n\n        if re.match(regex2, path):\n            search_match = re.search(regex2, path)\n            api_id = search_match.group(1)\n            stage = search_match.group(2)\n            relative_path_w_query_params = '/%s' % search_match.group(3)\n\n            relative_path, query_string_params = extract_query_string_params(path=relative_path_w_query_params)\n\n            path_map = get_rest_api_paths(rest_api_id=api_id)\n            try:\n                extracted_path, resource = get_resource_for_path(path=relative_path, path_map=path_map)\n            except Exception:\n                return make_error('Unable to find path %s' % path, 404)\n\n            integrations = resource.get('resourceMethods', {})\n            integration = integrations.get(method, {})\n            if not integration:\n                integration = integrations.get('ANY', {})\n            integration = integration.get('methodIntegration')\n            if not integration:\n\n                if method == 'OPTIONS' and 'Origin' in headers:\n                    # default to returning CORS headers if this is an OPTIONS request\n                    return get_cors_response(headers)\n\n                return make_error('Unable to find integration for path %s' % path, 404)\n\n            uri = integration.get('uri')\n            if method == 'POST' and integration['type'] == 'AWS':\n                if uri.endswith('kinesis:action/PutRecords'):\n                    template = integration['requestTemplates'][APPLICATION_JSON]\n                    new_request = aws_stack.render_velocity_template(template, data)\n\n                    # forward records to target kinesis stream\n                    headers = aws_stack.mock_aws_request_headers(service='kinesis')\n                    headers['X-Amz-Target'] = kinesis_listener.ACTION_PUT_RECORDS\n                    result = common.make_http_request(url=TEST_KINESIS_URL,\n                        method='POST', data=new_request, headers=headers)\n                    return result\n                else:\n                    msg = 'API Gateway action uri \"%s\" not yet implemented' % uri\n                    LOGGER.warning(msg)\n                    return make_error(msg, 404)\n\n            elif integration['type'] == 'AWS_PROXY':\n                if uri.startswith('arn:aws:apigateway:') and ':lambda:path' in uri:\n                    func_arn = uri.split(':lambda:path')[1].split('functions/')[1].split('/invocations')[0]\n                    account_id = uri.split(':lambda:path')[1].split(':function:')[0].split(':')[-1]\n                    data_str = json.dumps(data) if isinstance(data, dict) else data\n\n                    source_ip = headers['X-Forwarded-For'].split(',')[-2]\n\n                    # Sample request context:\n                    # https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-create-api-as-simple-proxy-for-lambda-test\n                    request_context = {\n                        'path': relative_path,\n                        'accountId': account_id,\n                        'resourceId': resource.get('id'),\n                        'stage': stage,\n                        'identity': {\n                            'accountId': account_id,\n                            'sourceIp': source_ip,\n                            'userAgent': headers['User-Agent'],\n                        }\n                    }\n\n                    try:\n                        path_params = extract_path_params(path=relative_path, extracted_path=extracted_path)\n                    except Exception:\n                        path_params = {}\n\n                    result = lambda_api.process_apigateway_invocation(func_arn, relative_path, data_str,\n                        headers, path_params=path_params, query_string_params=query_string_params,\n                        method=method, resource_path=path, request_context=request_context)\n\n                    if isinstance(result, FlaskResponse):\n                        return flask_to_requests_response(result)\n\n                    response = Response()\n                    parsed_result = result if isinstance(result, dict) else json.loads(result)\n                    parsed_result = common.json_safe(parsed_result)\n                    response.status_code = int(parsed_result.get('statusCode', 200))\n                    response.headers.update(parsed_result.get('headers', {}))\n                    try:\n                        if isinstance(parsed_result['body'], dict):\n                            response._content = json.dumps(parsed_result['body'])\n                        else:\n                            response._content = parsed_result['body']\n                    except Exception:\n                        response._content = '{}'\n                    return response\n                else:\n                    msg = 'API Gateway action uri \"%s\" not yet implemented' % uri\n                    LOGGER.warning(msg)\n                    return make_error(msg, 404)\n\n            elif integration['type'] == 'HTTP':\n                function = getattr(requests, method.lower())\n                if isinstance(data, dict):\n                    data = json.dumps(data)\n                result = function(integration['uri'], data=data, headers=headers)\n                return result\n\n            else:\n                msg = ('API Gateway integration type \"%s\" for method \"%s\" not yet implemented' %\n                       (integration['type'], method))\n                LOGGER.warning(msg)\n                return make_error(msg, 404)\n\n            return 200\n\n        if re.match(PATH_REGEX_AUTHORIZERS, path):\n            return handle_authorizers(method, path, data, headers)\n\n        return True\n\n\n# instantiate listener\nUPDATE_APIGATEWAY = ProxyListenerApiGateway()\n", "path": "localstack/services/apigateway/apigateway_listener.py"}]}