Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat: API Gateway REST API v1 — complete control and data plane (#2) (#12)

Nahuel Nucera0ef45048827c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac92b17b..cdb3850b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,40 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [1.0.6] — 2026-03-27
+
+### Added
+- **API Gateway REST API v1** (`services/apigateway_v1.py`) — complete control plane and data plane
+ - Full resource tree: `CreateRestApi`, `GetRestApi`, `GetRestApis`, `UpdateRestApi`, `DeleteRestApi`
+ - Resources: `CreateResource`, `GetResource`, `GetResources`, `UpdateResource`, `DeleteResource`
+ - Methods: `PutMethod`, `GetMethod`, `DeleteMethod`, `UpdateMethod`
+ - Method responses: `PutMethodResponse`, `GetMethodResponse`, `DeleteMethodResponse`
+ - Integrations: `PutIntegration`, `GetIntegration`, `DeleteIntegration`, `UpdateIntegration`
+ - Integration responses: `PutIntegrationResponse`, `GetIntegrationResponse`, `DeleteIntegrationResponse`
+ - Stages: `CreateStage`, `GetStage`, `GetStages`, `UpdateStage`, `DeleteStage`
+ - Deployments: `CreateDeployment`, `GetDeployment`, `GetDeployments`, `UpdateDeployment`, `DeleteDeployment`
+ - Authorizers: `CreateAuthorizer`, `GetAuthorizer`, `GetAuthorizers`, `UpdateAuthorizer`, `DeleteAuthorizer`
+ - Models: `CreateModel`, `GetModel`, `GetModels`, `DeleteModel`
+ - API keys: `CreateApiKey`, `GetApiKey`, `GetApiKeys`, `UpdateApiKey`, `DeleteApiKey`
+ - Usage plans: `CreateUsagePlan`, `GetUsagePlan`, `GetUsagePlans`, `UpdateUsagePlan`, `DeleteUsagePlan`, `CreateUsagePlanKey`, `GetUsagePlanKeys`, `DeleteUsagePlanKey`
+ - Domain names: `CreateDomainName`, `GetDomainName`, `GetDomainNames`, `DeleteDomainName`
+ - Base path mappings: `CreateBasePathMapping`, `GetBasePathMapping`, `GetBasePathMappings`, `DeleteBasePathMapping`
+ - Tags: `TagResource`, `UntagResource`, `GetTags`
+ - Data plane: execute-api requests routed by host header (`{apiId}.execute-api.localhost`)
+ - Lambda proxy format 1.0 (AWS_PROXY) — full `requestContext` with `requestTime`, `requestTimeEpoch`, `path`, `protocol`, `multiValueHeaders`; supports both apigateway URI form and plain `arn:aws:lambda:` ARN
+ - HTTP proxy (HTTP_PROXY) forwarding to arbitrary HTTP backends
+ - MOCK integration — selects response by `selectionPattern`, applies `responseParameters` to HTTP response headers, returns `responseTemplates` body
+ - Resource tree path matching with `{param}` placeholders and `{proxy+}` greedy segments
+ - JSON Patch support for all `PATCH` operations (`patchOperations`)
+ - `CreateDeployment` populates `apiSummary` from all configured resources and methods
+ - All timestamps (`createdDate`, `lastUpdatedDate`) returned as ISO 8601 strings — boto3 parses them as `datetime` objects
+ - Error responses use `type` field matching AWS API Gateway v1 format
+ - State persistence via `get_state()` / `load_persisted_state()`
+ - v1 and v2 APIs coexist on the same port without conflict
+- 434 integration tests — all passing, including against Docker image
+
+---
+
## [1.0.5] — 2026-03-26
### Fixed
@@ -174,7 +208,6 @@ Initial public release. Built as a free, open-source alternative to LocalStack.
## Roadmap
### Planned
-- API Gateway REST API (v1) — resource trees, methods, integration types, deployment stages
- Cognito (user pools, sign-up/sign-in)
- Route53 (hosted zones, record sets)
- ACM (certificate management)
diff --git a/README.md b/README.md
index fc00dc69..6d3e61ff 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@
LocalStack recently moved its core services behind a paid plan. If you relied on LocalStack Community for local development and CI/CD pipelines, MiniStack is your free alternative.
-- **21 AWS services** emulated on a single port (4566)
+- **22 AWS services** emulated on a single port (4566)
- **Drop-in compatible** — works with `boto3`, AWS CLI, Terraform, CDK, Pulumi, any SDK
- **Real infrastructure** — RDS spins up actual Postgres/MySQL containers, ElastiCache spins up real Redis, Athena runs real SQL via DuckDB, ECS runs real Docker containers
- **Tiny footprint** — ~150MB image, ~30MB RAM at idle vs LocalStack's ~1GB image and ~500MB RAM
@@ -188,6 +188,7 @@ sfn.create_state_machine(
| **SES** | SendEmail, SendRawEmail, SendTemplatedEmail, SendBulkTemplatedEmail, VerifyEmailIdentity, VerifyEmailAddress, VerifyDomainIdentity, VerifyDomainDkim, ListIdentities, GetIdentityVerificationAttributes, GetIdentityDkimAttributes, DeleteIdentity, GetSendQuota, GetSendStatistics, CreateConfigurationSet, DeleteConfigurationSet, DescribeConfigurationSet, ListConfigurationSets, CreateTemplate, GetTemplate, UpdateTemplate, DeleteTemplate, ListTemplates | Emails stored in-memory, not sent |
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel |
| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD |
+| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |
### Infrastructure Services (with real Docker execution)
@@ -346,7 +347,7 @@ ecs.stop_task(cluster="dev", task=task_arn)
When `PERSIST_STATE=1`, MiniStack saves service state to `STATE_DIR` on shutdown and reloads it on startup. Writes are atomic (write-to-tmp then rename) to prevent corruption on crash.
-Services currently supporting persistence: **API Gateway**
+Services currently supporting persistence: **API Gateway v1**, **API Gateway v2**
```bash
docker run -p 4566:4566 \
@@ -408,19 +409,19 @@ pip install boto3 pytest duckdb docker cbor2
# Start MiniStack
docker compose up -d
-# Run the full test suite (377 tests across all 21 services)
+# Run the full test suite (434 tests across all 21 services)
pytest tests/ -v
```
Expected output:
```
-collected 377 items
+collected 434 items
tests/test_services.py::test_s3_create_bucket PASSED
...
-tests/test_services.py::test_lambda_function_url_config PASSED
+tests/test_services.py::test_apigwv1_execute_mock_response_parameters PASSED
-377 passed in ~12s
+434 passed in ~60s
```
---
@@ -505,6 +506,7 @@ config:
| **Athena (real SQL via DuckDB)** | ✅ | ❌ | ✅ |
| **Glue Data Catalog + Jobs** | ✅ | ❌ | ✅ |
| **API Gateway v2 (HTTP API)** | ✅ | ✅ | ✅ |
+| **API Gateway v1 (REST API)** | ✅ | ✅ | ✅ |
| Cognito | ❌ | ✅ | ✅ |
| CloudFormation | ❌ | partial | ✅ |
| Cost | **Free** | Was free, now paid | $35+/mo |
diff --git a/app.py b/app.py
index 4400c8bf..9ac10e49 100644
--- a/app.py
+++ b/app.py
@@ -23,6 +23,7 @@ from services import s3, sqs, sns, dynamodb, lambda_svc, secretsmanager, cloudwa
from services import ssm, eventbridge, kinesis, cloudwatch, ses, stepfunctions
from services import ecs, rds, elasticache, glue, athena
from services import apigateway
+from services import apigateway_v1
from services.iam_sts import handle_iam_request, handle_sts_request
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
@@ -170,9 +171,14 @@ async def app(scope, receive, send):
stage = path_parts[0] if path_parts else "$default"
execute_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"
try:
- status, resp_headers, resp_body = await apigateway.handle_execute(
- api_id, stage, execute_path, method, headers, body, query_params
- )
+ if api_id in apigateway_v1._rest_apis:
+ status, resp_headers, resp_body = await apigateway_v1.handle_execute(
+ api_id, stage, method, execute_path, headers, body, query_params
+ )
+ else:
+ status, resp_headers, resp_body = await apigateway.handle_execute(
+ api_id, stage, execute_path, method, headers, body, query_params
+ )
except Exception as e:
logger.exception(f"Error in execute-api dispatch: {e}")
status, resp_headers, resp_body = 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()
@@ -244,7 +250,10 @@ async def _handle_lifespan(scope, receive, send):
elif message["type"] == "lifespan.shutdown":
logger.info("MiniStack shutting down...")
if PERSIST_STATE:
- save_all({"apigateway": apigateway.get_state})
+ save_all({
+ "apigateway": apigateway.get_state,
+ "apigateway_v1": apigateway_v1.get_state,
+ })
await send({"type": "lifespan.shutdown.complete"})
return
@@ -255,6 +264,10 @@ def _load_persisted_state():
if data:
apigateway.load_persisted_state(data)
logger.info("Loaded persisted state for apigateway")
+ data_v1 = load_state("apigateway_v1")
+ if data_v1:
+ apigateway_v1.load_persisted_state(data_v1)
+ logger.info("Loaded persisted state for apigateway_v1")
def _run_init_scripts():
@@ -303,6 +316,7 @@ def _reset_all_state():
(rds, rds.reset), (elasticache, elasticache.reset),
(glue, glue.reset), (athena, athena.reset),
(apigateway, apigateway.reset),
+ (apigateway_v1, apigateway_v1.reset),
]:
try:
fn()
diff --git a/core/router.py b/core/router.py
index a5474e55..ce59827e 100644
--- a/core/router.py
+++ b/core/router.py
@@ -252,6 +252,9 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
path_lower = path.lower()
if path_lower.startswith("/v2/apis"):
return "apigateway"
+ if (path_lower.startswith("/restapis") or path_lower.startswith("/apikeys")
+ or path_lower.startswith("/usageplans") or path_lower.startswith("/domainnames")):
+ return "apigateway"
if path_lower.startswith("/2015-03-31/functions"):
return "lambda"
if path_lower.startswith(("/clusters", "/taskdefinitions", "/tasks", "/services", "/stoptask")):
diff --git a/services/apigateway.py b/services/apigateway.py
index fa4f95de..09331b7c 100644
--- a/services/apigateway.py
+++ b/services/apigateway.py
@@ -107,12 +107,17 @@ def load_persisted_state(data: dict) -> None:
async def handle_request(method, path, headers, body, query_params):
"""Route API Gateway v2 control plane requests."""
+ # Dispatch v1 REST API requests first
+ parts = [p for p in path.strip("/").split("/") if p]
+ if parts and parts[0] in ("restapis", "apikeys", "usageplans", "domainnames", "tags"):
+ from services import apigateway_v1
+ return await apigateway_v1.handle_request(method, path, headers, body, query_params)
+
try:
data = json.loads(body) if body else {}
except json.JSONDecodeError:
data = {}
- parts = [p for p in path.strip("/").split("/") if p]
# Minimum expected: ["v2", <resource>]
if not parts or parts[0] != "v2":
diff --git a/services/apigateway_v1.py b/services/apigateway_v1.py
new file mode 100644
index 00000000..3e7ff47d
--- /dev/null
+++ b/services/apigateway_v1.py
@@ -0,0 +1,1518 @@
+"""
+API Gateway REST API v1 Emulator.
+
+Control plane endpoints implemented:
+ POST /restapis — CreateRestApi
+ GET /restapis — GetRestApis
+ GET /restapis/{id} — GetRestApi
+ PATCH /restapis/{id} — UpdateRestApi
+ DELETE /restapis/{id} — DeleteRestApi
+ GET /restapis/{id}/resources — GetResources
+ GET /restapis/{id}/resources/{resourceId} — GetResource
+ POST /restapis/{id}/resources/{parentId} — CreateResource
+ PATCH /restapis/{id}/resources/{resourceId} — UpdateResource
+ DELETE /restapis/{id}/resources/{resourceId} — DeleteResource
+ PUT /restapis/{id}/resources/{resourceId}/methods/{httpMethod} — PutMethod
+ GET /restapis/{id}/resources/{resourceId}/methods/{httpMethod} — GetMethod
+ DELETE /restapis/{id}/resources/{resourceId}/methods/{httpMethod} — DeleteMethod
+ PUT /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/responses/{code} — PutMethodResponse
+ GET /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/responses/{code} — GetMethodResponse
+ DELETE /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/responses/{code} — DeleteMethodResponse
+ PUT /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/integration — PutIntegration
+ GET /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/integration — GetIntegration
+ DELETE /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/integration — DeleteIntegration
+ PUT /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{code} — PutIntegrationResponse
+ GET /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{code} — GetIntegrationResponse
+ DELETE /restapis/{id}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{code} — DeleteIntegrationResponse
+ POST /restapis/{id}/deployments — CreateDeployment
+ GET /restapis/{id}/deployments — GetDeployments
+ GET /restapis/{id}/deployments/{deploymentId} — GetDeployment
+ PATCH /restapis/{id}/deployments/{deploymentId} — UpdateDeployment
+ DELETE /restapis/{id}/deployments/{deploymentId} — DeleteDeployment
+ POST /restapis/{id}/stages — CreateStage
+ GET /restapis/{id}/stages — GetStages
+ GET /restapis/{id}/stages/{stageName} — GetStage
+ PATCH /restapis/{id}/stages/{stageName} — UpdateStage
+ DELETE /restapis/{id}/stages/{stageName} — DeleteStage
+ POST /restapis/{id}/authorizers — CreateAuthorizer
+ GET /restapis/{id}/authorizers — GetAuthorizers
+ GET /restapis/{id}/authorizers/{authorizerId} — GetAuthorizer
+ PATCH /restapis/{id}/authorizers/{authorizerId} — UpdateAuthorizer
+ DELETE /restapis/{id}/authorizers/{authorizerId} — DeleteAuthorizer
+ POST /restapis/{id}/models — CreateModel
+ GET /restapis/{id}/models — GetModels
+ GET /restapis/{id}/models/{modelName} — GetModel
+ DELETE /restapis/{id}/models/{modelName} — DeleteModel
+ GET /apikeys — GetApiKeys
+ POST /apikeys — CreateApiKey
+ GET /apikeys/{keyId} — GetApiKey
+ DELETE /apikeys/{keyId} — DeleteApiKey
+ GET /usageplans — GetUsagePlans
+ POST /usageplans — CreateUsagePlan
+ GET /usageplans/{planId} — GetUsagePlan
+ DELETE /usageplans/{planId} — DeleteUsagePlan
+ GET /usageplans/{planId}/keys — GetUsagePlanKeys
+ POST /usageplans/{planId}/keys — CreateUsagePlanKey
+ DELETE /usageplans/{planId}/keys/{keyId} — DeleteUsagePlanKey
+ GET /domainnames — GetDomainNames
+ POST /domainnames — CreateDomainName
+ GET /domainnames/{domainName} — GetDomainName
+ DELETE /domainnames/{domainName} — DeleteDomainName
+ GET /tags/{resourceArn} — GetTags
+ PUT /tags/{resourceArn} — TagResource
+ DELETE /tags/{resourceArn} — UntagResource
+
+Data plane:
+ Requests to /{apiId}.execute-api.localhost/{stage}/{path} are dispatched
+ when api_id is found in _rest_apis.
+"""
+
+import json
+import time
+import datetime
+import logging
+
+from core.responses import new_uuid
+
+
+def _now_iso():
+ """Return current UTC time as ISO 8601 string matching AWS format."""
+ return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
+
+logger = logging.getLogger("apigateway_v1")
+
+ACCOUNT_ID = "000000000000"
+REGION = "us-east-1"
+
+# ---- Module-level state ----
+_rest_apis: dict = {} # rest_api_id -> RestApi
+_resources: dict = {} # rest_api_id -> {resource_id -> Resource}
+_stages_v1: dict = {} # rest_api_id -> {stage_name -> Stage}
+_deployments_v1: dict = {} # rest_api_id -> {deployment_id -> Deployment}
+_authorizers_v1: dict = {} # rest_api_id -> {authorizer_id -> Authorizer}
+_models: dict = {} # rest_api_id -> {model_id -> Model}
+_api_keys: dict = {} # key_id -> ApiKey
+_usage_plans: dict = {} # plan_id -> UsagePlan
+_usage_plan_keys: dict = {} # plan_id -> {key_id -> UsagePlanKey}
+_domain_names: dict = {} # domain_name -> DomainName
+_base_path_mappings: dict = {} # domain_name -> {base_path -> BasePathMapping}
+_v1_tags: dict = {} # resource_arn -> {key -> value}
+
+
+# ---- Helpers ----
+
+def _new_id():
+ """Return a 10-char hex id."""
+ return new_uuid().replace("-", "")[:10]
+
+
+def _v1_response(data, status=200):
+ """API Gateway v1 uses application/json."""
+ return status, {"Content-Type": "application/json"}, json.dumps(data).encode()
+
+
+def _v1_error(code, message, status):
+ return status, {"Content-Type": "application/json"}, json.dumps({"message": message, "type": code}).encode()
+
+
+def _rest_api_arn(api_id):
+ return f"arn:aws:apigateway:{REGION}::/restapis/{api_id}"
+
+
+def _compute_path(api_id, resource_id):
+ """Walk the parent chain to build the full resource path."""
+ resources = _resources.get(api_id, {})
+ parts = []
+ rid = resource_id
+ while rid:
+ r = resources.get(rid)
+ if not r:
+ break
+ pp = r.get("pathPart", "")
+ if pp:
+ parts.append(pp)
+ rid = r.get("parentId")
+ if not parts:
+ return "/"
+ parts.reverse()
+ return "/" + "/".join(parts)
+
+
+def _apply_patch(obj, patch_ops):
+ """Apply JSON Patch operations (replace/add/remove) to a dict in place."""
+ for op in patch_ops:
+ operation = op.get("op", "replace")
+ path = op.get("path", "")
+ value = op.get("value")
+
+ # Strip leading slash and split
+ keys = path.lstrip("/").split("/")
+ if not keys or keys == [""]:
+ continue
+
+ if operation in ("replace", "add"):
+ if len(keys) == 1:
+ obj[keys[0]] = value
+ else:
+ # Walk into nested dicts, create if needed
+ target = obj
+ for k in keys[:-1]:
+ if k not in target or not isinstance(target[k], dict):
+ target[k] = {}
+ target = target[k]
+ target[keys[-1]] = value
+ elif operation == "remove":
+ if len(keys) == 1:
+ obj.pop(keys[0], None)
+ else:
+ target = obj
+ for k in keys[:-1]:
+ if not isinstance(target.get(k), dict):
+ break
+ target = target[k]
+ else:
+ target.pop(keys[-1], None)
+ return obj
+
+
+def _match_resource_tree(api_id, segments):
+ """Match path segments against the resource tree. Returns (resource, path_params) or (None, {})."""
+ resources = _resources.get(api_id, {})
+ root = next((r for r in resources.values() if r.get("path") == "/"), None)
+ if not root:
+ return None, {}
+ if not segments or segments == [""]:
+ return root, {}
+ return _match_recursive(resources, root["id"], segments, {})
+
+
+def _match_recursive(resources, parent_id, segments, params):
+ if not segments:
+ return None, params
+ segment = segments[0]
+ remaining = segments[1:]
+ children = [r for r in resources.values() if r.get("parentId") == parent_id]
+ for child in children:
+ pp = child.get("pathPart", "")
+ if pp.endswith("+}") and pp.startswith("{"):
+ # greedy {proxy+}
+ param_name = pp[1:-2]
+ new_params = dict(params)
+ new_params[param_name] = "/".join([segment] + list(remaining))
+ return child, new_params
+ elif pp.startswith("{") and pp.endswith("}"):
+ param_name = pp[1:-1]
+ new_params = dict(params)
+ new_params[param_name] = segment
+ if not remaining:
+ return child, new_params
+ result, rp = _match_recursive(resources, child["id"], list(remaining), new_params)
+ if result:
+ return result, rp
+ elif pp == segment:
+ if not remaining:
+ return child, params
+ result, rp = _match_recursive(resources, child["id"], list(remaining), dict(params))
+ if result:
+ return result, rp
+ return None, params
+
+
+async def _call_lambda(func_name, event):
+ """Invoke a Lambda function and return the parsed response dict."""
+ from services import lambda_svc
+ from core.lambda_runtime import get_or_create_worker
+
+ if func_name not in lambda_svc._functions:
+ return None, f"Lambda function '{func_name}' not found"
+
+ func_data = lambda_svc._functions[func_name]
+ code_zip = func_data.get("code_zip")
+
+ if code_zip and func_data["config"]["Runtime"].startswith("python"):
+ worker = get_or_create_worker(func_name, func_data["config"], code_zip)
+ result = worker.invoke(event, new_uuid())
+ if result.get("status") == "error":
+ return None, result.get("error", "Lambda invocation error")
+ return result.get("result", {}), None
+ else:
+ return {"statusCode": 200, "body": "Mock response"}, None
+
+
+# ---- Persistence hooks ----
+
+def get_state():
+ """Return full module state for persistence."""
+ return {
+ "rest_apis": _rest_apis,
+ "resources": _resources,
+ "stages_v1": _stages_v1,
+ "deployments_v1": _deployments_v1,
+ "authorizers_v1": _authorizers_v1,
+ "models": _models,
+ "api_keys": _api_keys,
+ "usage_plans": _usage_plans,
+ "usage_plan_keys": _usage_plan_keys,
+ "domain_names": _domain_names,
+ "base_path_mappings": _base_path_mappings,
+ "v1_tags": _v1_tags,
+ }
+
+
+def load_persisted_state(data):
+ """Restore module state from a previously persisted snapshot."""
+ _rest_apis.update(data.get("rest_apis", {}))
+ _resources.update(data.get("resources", {}))
+ _stages_v1.update(data.get("stages_v1", {}))
+ _deployments_v1.update(data.get("deployments_v1", {}))
+ _authorizers_v1.update(data.get("authorizers_v1", {}))
+ _models.update(data.get("models", {}))
+ _api_keys.update(data.get("api_keys", {}))
+ _usage_plans.update(data.get("usage_plans", {}))
+ _usage_plan_keys.update(data.get("usage_plan_keys", {}))
+ _domain_names.update(data.get("domain_names", {}))
+ _base_path_mappings.update(data.get("base_path_mappings", {}))
+ _v1_tags.update(data.get("v1_tags", {}))
+
+
+def reset():
+ """Clear all module state."""
+ _rest_apis.clear()
+ _resources.clear()
+ _stages_v1.clear()
+ _deployments_v1.clear()
+ _authorizers_v1.clear()
+ _models.clear()
+ _api_keys.clear()
+ _usage_plans.clear()
+ _usage_plan_keys.clear()
+ _domain_names.clear()
+ _base_path_mappings.clear()
+ _v1_tags.clear()
+
+
+# ---- Control plane router ----
+
+async def handle_request(method, path, headers, body, query_params):
+ """Route API Gateway v1 REST API control plane requests."""
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ data = {}
+
+ parts = [p for p in path.strip("/").split("/") if p]
+
+ if not parts:
+ return _v1_error("NotFoundException", f"Unknown path: {path}", 404)
+
+ top = parts[0]
+
+ if top == "tags":
+ # /tags/{resourceArn} — ARN may contain slashes
+ resource_arn = "/".join(parts[1:]) if len(parts) > 1 else ""
+ if method == "GET":
+ return _get_v1_tags(resource_arn)
+ if method in ("PUT", "POST"):
+ return _tag_v1_resource(resource_arn, data)
+ if method == "DELETE":
+ tag_keys = query_params.get("tagKeys", [])
+ if isinstance(tag_keys, str):
+ tag_keys = [tag_keys]
+ return _untag_v1_resource(resource_arn, tag_keys)
+
+ if top == "apikeys":
+ key_id = parts[1] if len(parts) > 1 else None
+ if not key_id:
+ if method == "GET":
+ return _get_api_keys()
+ if method == "POST":
+ return _create_api_key(data)
+ else:
+ if method == "GET":
+ return _get_api_key(key_id)
+ if method == "DELETE":
+ return _delete_api_key(key_id)
+ if method == "PATCH":
+ return _update_api_key(key_id, data)
+
+ if top == "usageplans":
+ plan_id = parts[1] if len(parts) > 1 else None
+ sub = parts[2] if len(parts) > 2 else None
+ sub_id = parts[3] if len(parts) > 3 else None
+ if not plan_id:
+ if method == "GET":
+ return _get_usage_plans()
+ if method == "POST":
+ return _create_usage_plan(data)
+ elif sub == "keys":
+ if not sub_id:
+ if method == "GET":
+ return _get_usage_plan_keys(plan_id)
+ if method == "POST":
+ return _create_usage_plan_key(plan_id, data)
+ else:
+ if method == "DELETE":
+ return _delete_usage_plan_key(plan_id, sub_id)
+ else:
+ if method == "GET":
+ return _get_usage_plan(plan_id)
+ if method == "DELETE":
+ return _delete_usage_plan(plan_id)
+ if method == "PATCH":
+ return _update_usage_plan(plan_id, data)
+
+ if top == "domainnames":
+ domain_name = parts[1] if len(parts) > 1 else None
+ sub = parts[2] if len(parts) > 2 else None
+ sub_id = parts[3] if len(parts) > 3 else None
+ if not domain_name:
+ if method == "GET":
+ return _get_domain_names()
+ if method == "POST":
+ return _create_domain_name(data)
+ elif sub == "basepathmappings":
+ base_path = sub_id
+ if not base_path:
+ if method == "GET":
+ return _get_base_path_mappings(domain_name)
+ if method == "POST":
+ return _create_base_path_mapping(domain_name, data)
+ else:
+ if method == "GET":
+ return _get_base_path_mapping(domain_name, base_path)
+ if method == "DELETE":
+ return _delete_base_path_mapping(domain_name, base_path)
+ else:
+ if method == "GET":
+ return _get_domain_name(domain_name)
+ if method == "DELETE":
+ return _delete_domain_name(domain_name)
+
+ if top == "restapis":
+ # /restapis
+ if len(parts) == 1:
+ if method == "POST":
+ return _create_rest_api(data)
+ if method == "GET":
+ return _get_rest_apis()
+
+ api_id = parts[1]
+
+ # /restapis/{id}
+ if len(parts) == 2:
+ if method == "GET":
+ return _get_rest_api(api_id)
+ if method == "DELETE":
+ return _delete_rest_api(api_id)
+ if method == "PATCH":
+ return _update_rest_api(api_id, data)
+
+ sub = parts[2] if len(parts) > 2 else None
+
+ # /restapis/{id}/resources[/{resourceId}[/...]]
+ if sub == "resources":
+ resource_id = parts[3] if len(parts) > 3 else None
+ method_part = parts[4] if len(parts) > 4 else None
+ http_method = parts[5] if len(parts) > 5 else None
+ after_method = parts[6] if len(parts) > 6 else None
+ after_method_id = parts[7] if len(parts) > 7 else None
+
+ if not resource_id:
+ # GET /restapis/{id}/resources
+ if method == "GET":
+ return _get_resources(api_id)
+
+ elif method_part is None:
+ # /restapis/{id}/resources/{resourceId}
+ if method == "GET":
+ return _get_resource(api_id, resource_id)
+ if method == "POST":
+ # CreateResource: POST /restapis/{id}/resources/{parentId}
+ return _create_resource(api_id, resource_id, data)
+ if method == "PATCH":
+ return _update_resource(api_id, resource_id, data)
+ if method == "DELETE":
+ return _delete_resource(api_id, resource_id)
+
+ elif method_part == "methods":
+ if http_method is None:
+ return _v1_error("NotFoundException", "Method not specified", 404)
+
+ if after_method is None:
+ # /restapis/{id}/resources/{resourceId}/methods/{httpMethod}
+ if method == "PUT":
+ return _put_method(api_id, resource_id, http_method, data)
+ if method == "GET":
+ return _get_method(api_id, resource_id, http_method)
+ if method == "DELETE":
+ return _delete_method(api_id, resource_id, http_method)
+ if method == "PATCH":
+ return _update_method(api_id, resource_id, http_method, data)
+
+ elif after_method == "responses":
+ status_code = after_method_id
+ if not status_code:
+ return _v1_error("NotFoundException", "Status code not specified", 404)
+ if method == "PUT":
+ return _put_method_response(api_id, resource_id, http_method, status_code, data)
+ if method == "GET":
+ return _get_method_response(api_id, resource_id, http_method, status_code)
+ if method == "DELETE":
+ return _delete_method_response(api_id, resource_id, http_method, status_code)
+
+ elif after_method == "integration":
+ # Check for integration/responses/{statusCode}
+ int_sub = parts[7] if len(parts) > 7 else None
+ int_sub_id = parts[8] if len(parts) > 8 else None
+
+ if after_method_id is None and int_sub is None:
+ # /.../{httpMethod}/integration
+ if method == "PUT":
+ return _put_integration(api_id, resource_id, http_method, data)
+ if method == "GET":
+ return _get_integration(api_id, resource_id, http_method)
+ if method == "DELETE":
+ return _delete_integration(api_id, resource_id, http_method)
+ if method == "PATCH":
+ return _update_integration(api_id, resource_id, http_method, data)
+ elif after_method_id == "responses":
+ status_code = int_sub_id
+ if not status_code:
+ return _v1_error("NotFoundException", "Status code not specified", 404)
+ if method == "PUT":
+ return _put_integration_response(api_id, resource_id, http_method, status_code, data)
+ if method == "GET":
+ return _get_integration_response(api_id, resource_id, http_method, status_code)
+ if method == "DELETE":
+ return _delete_integration_response(api_id, resource_id, http_method, status_code)
+
+ # /restapis/{id}/deployments[/{deploymentId}]
+ elif sub == "deployments":
+ deployment_id = parts[3] if len(parts) > 3 else None
+ if not deployment_id:
+ if method == "POST":
+ return _create_deployment(api_id, data)
+ if method == "GET":
+ return _get_deployments(api_id)
+ else:
+ if method == "GET":
+ return _get_deployment(api_id, deployment_id)
+ if method == "PATCH":
+ return _update_deployment(api_id, deployment_id, data)
+ if method == "DELETE":
+ return _delete_deployment(api_id, deployment_id)
+
+ # /restapis/{id}/stages[/{stageName}]
+ elif sub == "stages":
+ stage_name = parts[3] if len(parts) > 3 else None
+ if not stage_name:
+ if method == "POST":
+ return _create_stage(api_id, data)
+ if method == "GET":
+ return _get_stages(api_id)
+ else:
+ if method == "GET":
+ return _get_stage(api_id, stage_name)
+ if method == "PATCH":
+ return _update_stage(api_id, stage_name, data)
+ if method == "DELETE":
+ return _delete_stage(api_id, stage_name)
+
+ # /restapis/{id}/authorizers[/{authorizerId}]
+ elif sub == "authorizers":
+ auth_id = parts[3] if len(parts) > 3 else None
+ if not auth_id:
+ if method == "POST":
+ return _create_authorizer(api_id, data)
+ if method == "GET":
+ return _get_authorizers(api_id)
+ else:
+ if method == "GET":
+ return _get_authorizer(api_id, auth_id)
+ if method == "PATCH":
+ return _update_authorizer(api_id, auth_id, data)
+ if method == "DELETE":
+ return _delete_authorizer(api_id, auth_id)
+
+ # /restapis/{id}/models[/{modelName}]
+ elif sub == "models":
+ model_name = parts[3] if len(parts) > 3 else None
+ if not model_name:
+ if method == "POST":
+ return _create_model(api_id, data)
+ if method == "GET":
+ return _get_models(api_id)
+ else:
+ if method == "GET":
+ return _get_model(api_id, model_name)
+ if method == "DELETE":
+ return _delete_model(api_id, model_name)
+
+ return _v1_error("NotFoundException", f"Unknown API Gateway v1 path: {path}", 404)
+
+
+# ---- Data plane ----
+
+async def handle_execute(api_id, stage_name, method, path, headers, body, query_params):
+ """Execute a v1 REST API request through a deployed stage (data plane)."""
+ api = _rest_apis.get(api_id)
+ if not api:
+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Not Found"}).encode()
+
+ stage = _stages_v1.get(api_id, {}).get(stage_name)
+ if not stage:
+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": f"Stage '{stage_name}' not found"}).encode()
+
+ # Match path against resource tree
+ segments = [s for s in path.strip("/").split("/") if s]
+ resource, path_params = _match_resource_tree(api_id, segments)
+
+ if not resource:
+ return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Missing Authentication Token"}).encode()
+
+ # Look up method
+ resource_methods = resource.get("resourceMethods", {})
+ method_obj = resource_methods.get(method) or resource_methods.get("ANY")
+ if not method_obj:
+ return 405, {"Content-Type": "application/json"}, json.dumps({"message": "Method Not Allowed"}).encode()
+
+ integration = method_obj.get("methodIntegration")
+ if not integration:
+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": "No integration configured"}).encode()
+
+ int_type = integration.get("type", "")
+
+ if int_type in ("AWS_PROXY", "AWS"):
+ return await _invoke_lambda_proxy_v1(
+ integration, api_id, stage_name, stage, resource, path, method,
+ headers, body, query_params, path_params
+ )
+ elif int_type in ("HTTP_PROXY", "HTTP"):
+ return await _invoke_http_proxy_v1(integration, path, method, headers, body, query_params)
+ elif int_type == "MOCK":
+ return _invoke_mock_v1(integration)
+ else:
+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": f"Unsupported integration type: {int_type}"}).encode()
+
+
+async def _invoke_lambda_proxy_v1(integration, api_id, stage_name, stage, resource, request_path, method, headers, body, query_params, path_params):
+ """Invoke Lambda with API Gateway v1 payload format 1.0."""
+ uri = integration.get("uri", "")
+ # Supported URI formats:
+ # 1. arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/arn:aws:lambda:{region}:{acct}:function:{name}/invocations
+ # 2. arn:aws:lambda:{region}:{acct}:function:{name}
+ # 3. plain function name: MyFunction
+ if "function:" in uri:
+ func_name = uri.split("function:")[-1].split("/")[0].split(":")[0]
+ else:
+ func_name = uri
+
+ qs_params = {k: v[0] for k, v in query_params.items()} if query_params else None
+ mv_qs_params = {k: list(v) for k, v in query_params.items()} if query_params else None
+
+ # Build single and multi-value header dicts
+ single_headers = {k: v if isinstance(v, str) else v[-1] for k, v in headers.items()}
+ multi_headers = {k: [v] if isinstance(v, str) else list(v) for k, v in headers.items()}
+
+ now_epoch_ms = int(time.time() * 1000)
+ request_time = datetime.datetime.utcnow().strftime("%d/%b/%Y:%H:%M:%S +0000")
+ request_id = new_uuid()
+
+ event = {
+ "version": "1.0",
+ "resource": resource["path"],
+ "path": request_path,
+ "httpMethod": method,
+ "headers": single_headers,
+ "multiValueHeaders": multi_headers,
+ "queryStringParameters": qs_params or None,
+ "multiValueQueryStringParameters": mv_qs_params or None,
+ "pathParameters": path_params or None,
+ "stageVariables": stage.get("variables") or None,
+ "requestContext": {
+ "accountId": ACCOUNT_ID,
+ "resourceId": resource["id"],
+ "stage": stage_name,
+ "requestId": request_id,
+ "extendedRequestId": request_id,
+ "requestTime": request_time,
+ "requestTimeEpoch": now_epoch_ms,
+ "path": f"/{stage_name}{request_path}",
+ "protocol": "HTTP/1.1",
+ "identity": {
+ "sourceIp": headers.get("x-forwarded-for", "127.0.0.1").split(",")[0].strip()
+ if isinstance(headers.get("x-forwarded-for", ""), str)
+ else "127.0.0.1",
+ "userAgent": headers.get("user-agent", ""),
+ },
+ "resourcePath": resource["path"],
+ "httpMethod": method,
+ "apiId": api_id,
+ },
+ "body": body.decode("utf-8", errors="replace") if body else None,
+ "isBase64Encoded": False,
+ }
+
+ lambda_response, err = await _call_lambda(func_name, event)
+ if err:
+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": err}).encode()
+
+ status = lambda_response.get("statusCode", 200)
+ resp_headers = {"Content-Type": "application/json"}
+ resp_headers.update(lambda_response.get("headers", {}))
+ resp_body = lambda_response.get("body", "")
+ if isinstance(resp_body, str):
+ resp_body = resp_body.encode()
+ elif isinstance(resp_body, dict):
+ resp_body = json.dumps(resp_body).encode()
+
+ return status, resp_headers, resp_body
+
+
+async def _invoke_http_proxy_v1(integration, path, method, headers, body, query_params):
+ """Forward a request to an HTTP backend."""
+ import urllib.request
+ import urllib.error
+
+ uri = integration.get("uri", "")
+ url = uri.rstrip("/") + path
+
+ req = urllib.request.Request(url, data=body or None, method=method)
+ for k, v in headers.items():
+ if k.lower() not in ("host", "content-length"):
+ req.add_header(k, v)
+ try:
+ with urllib.request.urlopen(req, timeout=30) as resp:
+ resp_body = resp.read()
+ resp_headers = {"Content-Type": resp.headers.get("Content-Type", "application/json")}
+ return resp.status, resp_headers, resp_body
+ except urllib.error.HTTPError as e:
+ return e.code, {"Content-Type": "application/json"}, e.read()
+ except Exception as ex:
+ return 502, {"Content-Type": "application/json"}, json.dumps({"message": str(ex)}).encode()
+
+
+def _invoke_mock_v1(integration):
+ """Return a MOCK integration response.
+
+ Selection: iterate integrationResponses in status-code order; the first
+ entry whose selectionPattern is empty (default) or matches "200" is used,
+ matching AWS behaviour for MOCK where the input is always treated as
+ successful (statusCode 200).
+ """
+ import re
+ int_responses = integration.get("integrationResponses", {})
+ if not int_responses:
+ return 200, {"Content-Type": "application/json"}, b"{}"
+
+ # AWS selects the response whose selectionPattern matches the integration
+ # status code. For MOCK the "status" is always 200 (success path).
+ selected = None
+ # Prefer an explicit "200" entry first
+ if "200" in int_responses:
+ selected = int_responses["200"]
+ else:
+ # Fall back to the entry with an empty / catch-all selectionPattern
+ for resp in int_responses.values():
+ pattern = resp.get("selectionPattern", "")
+ if not pattern:
+ selected = resp
+ break
+ if not selected:
+ selected = next(iter(int_responses.values()))
+
+ status = int(selected.get("statusCode", 200))
+ resp_headers = {"Content-Type": "application/json"}
+
+ # Apply responseParameters: map integration values to method response headers
+ for dest, src in selected.get("responseParameters", {}).items():
+ # dest: "method.response.header.X-Custom-Header"
+ if dest.startswith("method.response.header."):
+ header_name = dest[len("method.response.header."):]
+ # src is a static string value (quoted) or integration reference
+ value = src.strip("'") if src.startswith("'") else src
+ resp_headers[header_name] = value
+
+ body_template = selected.get("responseTemplates", {}).get("application/json", "")
+ if body_template:
+ return status, resp_headers, body_template.encode()
+ return status, resp_headers, b"{}"
+
+
+# ---- Control plane: REST APIs ----
+
+def _create_rest_api(data):
+ api_id = _new_id()[:8]
+ api = {
+ "id": api_id,
+ "name": data.get("name", "unnamed"),
+ "description": data.get("description", ""),
+ "createdDate": _now_iso(),
+ "version": data.get("version", ""),
+ "binaryMediaTypes": data.get("binaryMediaTypes", []),
+ "minimumCompressionSize": data.get("minimumCompressionSize"),
+ "apiKeySource": data.get("apiKeySource", "HEADER"),
+ "endpointConfiguration": data.get("endpointConfiguration", {"types": ["REGIONAL"]}),
+ "policy": data.get("policy"),
+ "tags": data.get("tags", {}),
+ "disableExecuteApiEndpoint": data.get("disableExecuteApiEndpoint", False),
+ }
+ _rest_apis[api_id] = api
+ _resources[api_id] = {}
+ _stages_v1[api_id] = {}
+ _deployments_v1[api_id] = {}
+ _authorizers_v1[api_id] = {}
+ _models[api_id] = {}
+
+ # Create root resource "/"
+ root_id = _new_id()[:8]
+ root_resource = {
+ "id": root_id,
+ "parentId": None,
+ "pathPart": "",
+ "path": "/",
+ "resourceMethods": {},
+ }
+ _resources[api_id][root_id] = root_resource
+
+ _v1_tags[_rest_api_arn(api_id)] = dict(data.get("tags", {}))
+ return _v1_response(api, 201)
+
+
+def _get_rest_api(api_id):
+ api = _rest_apis.get(api_id)
+ if not api:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_response(api)
+
+
+def _get_rest_apis():
+ return _v1_response({"item": list(_rest_apis.values()), "nextToken": None})
+
+
+def _update_rest_api(api_id, data):
+ api = _rest_apis.get(api_id)
+ if not api:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(api, patch_ops)
+ return _v1_response(api)
+
+
+def _delete_rest_api(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ _rest_apis.pop(api_id, None)
+ _resources.pop(api_id, None)
+ _stages_v1.pop(api_id, None)
+ _deployments_v1.pop(api_id, None)
+ _authorizers_v1.pop(api_id, None)
+ _models.pop(api_id, None)
+ _v1_tags.pop(_rest_api_arn(api_id), None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Resources ----
+
+def _get_resources(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_response({"item": list(_resources.get(api_id, {}).values())})
+
+
+def _get_resource(api_id, resource_id):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ return _v1_response(resource)
+
+
+def _create_resource(api_id, parent_id, data):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ if parent_id not in _resources.get(api_id, {}):
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ path_part = data.get("pathPart", "")
+ resource_id = _new_id()[:8]
+ resource = {
+ "id": resource_id,
+ "parentId": parent_id,
+ "pathPart": path_part,
+ "path": "",
+ "resourceMethods": {},
+ }
+ _resources[api_id][resource_id] = resource
+ # Compute the full path
+ resource["path"] = _compute_path(api_id, resource_id)
+ return _v1_response(resource, 201)
+
+
+def _update_resource(api_id, resource_id, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(resource, patch_ops)
+ # Recompute path if pathPart changed
+ resource["path"] = _compute_path(api_id, resource_id)
+ return _v1_response(resource)
+
+
+def _delete_resource(api_id, resource_id):
+ if resource_id not in _resources.get(api_id, {}):
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ _resources[api_id].pop(resource_id, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Methods ----
+
+def _put_method(api_id, resource_id, http_method, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = {
+ "httpMethod": http_method,
+ "authorizationType": data.get("authorizationType", "NONE"),
+ "authorizerId": data.get("authorizerId"),
+ "apiKeyRequired": data.get("apiKeyRequired", False),
+ "operationName": data.get("operationName", ""),
+ "requestParameters": data.get("requestParameters", {}),
+ "requestModels": data.get("requestModels", {}),
+ "methodResponses": {},
+ "methodIntegration": None,
+ }
+ resource["resourceMethods"][http_method] = method_obj
+ return _v1_response(method_obj, 201)
+
+
+def _get_method(api_id, resource_id, http_method):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ return _v1_response(method_obj)
+
+
+def _delete_method(api_id, resource_id, http_method):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ resource["resourceMethods"].pop(http_method, None)
+ return 204, {}, b""
+
+
+def _update_method(api_id, resource_id, http_method, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(method_obj, patch_ops)
+ return _v1_response(method_obj)
+
+
+# ---- Control plane: Method Responses ----
+
+def _put_method_response(api_id, resource_id, http_method, status_code, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ method_response = {
+ "statusCode": status_code,
+ "responseParameters": data.get("responseParameters", {}),
+ "responseModels": data.get("responseModels", {}),
+ }
+ method_obj["methodResponses"][status_code] = method_response
+ return _v1_response(method_response)
+
+
+def _get_method_response(api_id, resource_id, http_method, status_code):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ resp = method_obj["methodResponses"].get(status_code)
+ if not resp:
+ return _v1_error("NotFoundException", f"Invalid Response status code specified", 404)
+ return _v1_response(resp)
+
+
+def _delete_method_response(api_id, resource_id, http_method, status_code):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if method_obj:
+ method_obj["methodResponses"].pop(status_code, None)
+ return 204, {}, b""
+
+
+# ---- Control plane: Integration ----
+
+def _put_integration(api_id, resource_id, http_method, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ integration = {
+ "type": data.get("type", "AWS_PROXY"),
+ "httpMethod": data.get("httpMethod", "POST"),
+ "uri": data.get("uri", ""),
+ "connectionType": data.get("connectionType", "INTERNET"),
+ "credentials": data.get("credentials"),
+ "requestParameters": data.get("requestParameters", {}),
+ "requestTemplates": data.get("requestTemplates", {}),
+ "passthroughBehavior": data.get("passthroughBehavior", "WHEN_NO_MATCH"),
+ "timeoutInMillis": data.get("timeoutInMillis", 29000),
+ "cacheNamespace": resource_id,
+ "cacheKeyParameters": data.get("cacheKeyParameters", []),
+ "integrationResponses": {},
+ }
+ method_obj["methodIntegration"] = integration
+ return _v1_response(integration)
+
+
+def _get_integration(api_id, resource_id, http_method):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ integration = method_obj.get("methodIntegration")
+ if not integration:
+ return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ return _v1_response(integration)
+
+
+def _delete_integration(api_id, resource_id, http_method):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if method_obj:
+ method_obj["methodIntegration"] = None
+ return 204, {}, b""
+
+
+def _update_integration(api_id, resource_id, http_method, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ integration = method_obj.get("methodIntegration")
+ if not integration:
+ return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(integration, patch_ops)
+ return _v1_response(integration)
+
+
+# ---- Control plane: Integration Responses ----
+
+def _put_integration_response(api_id, resource_id, http_method, status_code, data):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ integration = method_obj.get("methodIntegration")
+ if not integration:
+ return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ int_response = {
+ "statusCode": status_code,
+ "selectionPattern": data.get("selectionPattern", ""),
+ "responseParameters": data.get("responseParameters", {}),
+ "responseTemplates": data.get("responseTemplates", {}),
+ "contentHandling": data.get("contentHandling"),
+ }
+ integration["integrationResponses"][status_code] = int_response
+ return _v1_response(int_response)
+
+
+def _get_integration_response(api_id, resource_id, http_method, status_code):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if not method_obj:
+ return _v1_error("NotFoundException", f"Invalid Method identifier specified", 404)
+ integration = method_obj.get("methodIntegration")
+ if not integration:
+ return _v1_error("NotFoundException", f"Invalid Integration identifier specified", 404)
+ resp = integration["integrationResponses"].get(status_code)
+ if not resp:
+ return _v1_error("NotFoundException", f"Invalid Response status code specified", 404)
+ return _v1_response(resp)
+
+
+def _delete_integration_response(api_id, resource_id, http_method, status_code):
+ resource = _resources.get(api_id, {}).get(resource_id)
+ if not resource:
+ return _v1_error("NotFoundException", f"Invalid Resource identifier specified", 404)
+ method_obj = resource["resourceMethods"].get(http_method)
+ if method_obj and method_obj.get("methodIntegration"):
+ method_obj["methodIntegration"]["integrationResponses"].pop(status_code, None)
+ return 204, {}, b""
+
+
+# ---- Helpers ----
+
+def _build_api_summary(api_id):
+ """Build the apiSummary structure: {path: {httpMethod: {authorizationScopes, apiKeyRequired}}}."""
+ summary = {}
+ for resource in _resources.get(api_id, {}).values():
+ path = resource.get("path", "/")
+ for http_method, method_obj in resource.get("resourceMethods", {}).items():
+ if path not in summary:
+ summary[path] = {}
+ summary[path][http_method] = {
+ "authorizationScopes": [],
+ "apiKeyRequired": method_obj.get("apiKeyRequired", False),
+ }
+ return summary
+
+
+# ---- Control plane: Deployments ----
+
+def _create_deployment(api_id, data):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ deployment_id = _new_id()[:8]
+ deployment = {
+ "id": deployment_id,
+ "description": data.get("description", ""),
+ "createdDate": _now_iso(),
+ "apiSummary": _build_api_summary(api_id),
+ }
+ _deployments_v1.setdefault(api_id, {})[deployment_id] = deployment
+
+ # If stageName is provided, create/update the stage automatically
+ stage_name = data.get("stageName")
+ if stage_name:
+ existing_stage = _stages_v1.get(api_id, {}).get(stage_name)
+ if existing_stage:
+ existing_stage["deploymentId"] = deployment_id
+ existing_stage["lastUpdatedDate"] = _now_iso()
+ else:
+ stage = {
+ "stageName": stage_name,
+ "deploymentId": deployment_id,
+ "description": data.get("stageDescription", ""),
+ "createdDate": _now_iso(),
+ "lastUpdatedDate": _now_iso(),
+ "variables": data.get("variables", {}),
+ "methodSettings": {},
+ "accessLogSettings": {},
+ "cacheClusterEnabled": False,
+ "cacheClusterSize": None,
+ "tracingEnabled": False,
+ "tags": {},
+ "documentationVersion": None,
+ }
+ _stages_v1.setdefault(api_id, {})[stage_name] = stage
+
+ return _v1_response(deployment, 201)
+
+
+def _get_deployments(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_response({"item": list(_deployments_v1.get(api_id, {}).values())})
+
+
+def _get_deployment(api_id, deployment_id):
+ deployment = _deployments_v1.get(api_id, {}).get(deployment_id)
+ if not deployment:
+ return _v1_error("NotFoundException", f"Invalid Deployment identifier specified", 404)
+ return _v1_response(deployment)
+
+
+def _update_deployment(api_id, deployment_id, data):
+ deployment = _deployments_v1.get(api_id, {}).get(deployment_id)
+ if not deployment:
+ return _v1_error("NotFoundException", f"Invalid Deployment identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(deployment, patch_ops)
+ return _v1_response(deployment)
+
+
+def _delete_deployment(api_id, deployment_id):
+ if deployment_id not in _deployments_v1.get(api_id, {}):
+ return _v1_error("NotFoundException", f"Invalid Deployment identifier specified", 404)
+ _deployments_v1[api_id].pop(deployment_id, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Stages ----
+
+def _create_stage(api_id, data):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ stage_name = data.get("stageName", "")
+ if not stage_name:
+ return _v1_error("BadRequestException", "Stage name is required", 400)
+ stage = {
+ "stageName": stage_name,
+ "deploymentId": data.get("deploymentId", ""),
+ "description": data.get("description", ""),
+ "createdDate": _now_iso(),
+ "lastUpdatedDate": _now_iso(),
+ "variables": data.get("variables", {}),
+ "methodSettings": data.get("methodSettings", {}),
+ "accessLogSettings": data.get("accessLogSettings", {}),
+ "cacheClusterEnabled": data.get("cacheClusterEnabled", False),
+ "cacheClusterSize": data.get("cacheClusterSize"),
+ "tracingEnabled": data.get("tracingEnabled", False),
+ "tags": data.get("tags", {}),
+ "documentationVersion": data.get("documentationVersion"),
+ }
+ _stages_v1.setdefault(api_id, {})[stage_name] = stage
+ return _v1_response(stage, 201)
+
+
+def _get_stages(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_response({"item": list(_stages_v1.get(api_id, {}).values())})
+
+
+def _get_stage(api_id, stage_name):
+ stage = _stages_v1.get(api_id, {}).get(stage_name)
+ if not stage:
+ return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
+ return _v1_response(stage)
+
+
+def _update_stage(api_id, stage_name, data):
+ stage = _stages_v1.get(api_id, {}).get(stage_name)
+ if not stage:
+ return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(stage, patch_ops)
+ stage["lastUpdatedDate"] = _now_iso()
+ return _v1_response(stage)
+
+
+def _delete_stage(api_id, stage_name):
+ if stage_name not in _stages_v1.get(api_id, {}):
+ return _v1_error("NotFoundException", f"Invalid Stage identifier specified", 404)
+ _stages_v1[api_id].pop(stage_name, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Authorizers ----
+
+def _create_authorizer(api_id, data):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ auth_id = _new_id()[:8]
+ authorizer = {
+ "id": auth_id,
+ "name": data.get("name", ""),
+ "type": data.get("type", "TOKEN"),
+ "authorizerUri": data.get("authorizerUri", ""),
+ "authorizerCredentials": data.get("authorizerCredentials"),
+ "identitySource": data.get("identitySource", "method.request.header.Authorization"),
+ "identityValidationExpression": data.get("identityValidationExpression", ""),
+ "authorizerResultTtlInSeconds": data.get("authorizerResultTtlInSeconds", 300),
+ "providerARNs": data.get("providerARNs", []),
+ }
+ _authorizers_v1.setdefault(api_id, {})[auth_id] = authorizer
+ return _v1_response(authorizer, 201)
+
+
+def _get_authorizers(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_response({"item": list(_authorizers_v1.get(api_id, {}).values())})
+
+
+def _get_authorizer(api_id, auth_id):
+ authorizer = _authorizers_v1.get(api_id, {}).get(auth_id)
+ if not authorizer:
+ return _v1_error("NotFoundException", f"Invalid Authorizer identifier specified", 404)
+ return _v1_response(authorizer)
+
+
+def _update_authorizer(api_id, auth_id, data):
+ authorizer = _authorizers_v1.get(api_id, {}).get(auth_id)
+ if not authorizer:
+ return _v1_error("NotFoundException", f"Invalid Authorizer identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(authorizer, patch_ops)
+ return _v1_response(authorizer)
+
+
+def _delete_authorizer(api_id, auth_id):
+ if auth_id not in _authorizers_v1.get(api_id, {}):
+ return _v1_error("NotFoundException", f"Invalid Authorizer identifier specified", 404)
+ _authorizers_v1[api_id].pop(auth_id, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Models ----
+
+def _create_model(api_id, data):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ model_name = data.get("name", "")
+ if not model_name:
+ return _v1_error("BadRequestException", "Model name is required", 400)
+ model = {
+ "id": _new_id()[:8],
+ "name": model_name,
+ "description": data.get("description", ""),
+ "schema": data.get("schema", ""),
+ "contentType": data.get("contentType", "application/json"),
+ }
+ _models.setdefault(api_id, {})[model_name] = model
+ return _v1_response(model, 201)
+
+
+def _get_models(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", f"Invalid API identifier specified", 404)
+ return _v1_response({"item": list(_models.get(api_id, {}).values())})
+
+
+def _get_model(api_id, model_name):
+ model = _models.get(api_id, {}).get(model_name)
+ if not model:
+ return _v1_error("NotFoundException", f"Invalid Model identifier specified", 404)
+ return _v1_response(model)
+
+
+def _delete_model(api_id, model_name):
+ if model_name not in _models.get(api_id, {}):
+ return _v1_error("NotFoundException", f"Invalid Model identifier specified", 404)
+ _models[api_id].pop(model_name, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: API Keys ----
+
+def _create_api_key(data):
+ key_id = _new_id()[:8]
+ key_value = new_uuid().replace("-", "")
+ api_key = {
+ "id": key_id,
+ "name": data.get("name", ""),
+ "description": data.get("description", ""),
+ "enabled": data.get("enabled", True),
+ "createdDate": _now_iso(),
+ "lastUpdatedDate": _now_iso(),
+ "value": key_value,
+ "stageKeys": data.get("stageKeys", []),
+ "tags": data.get("tags", {}),
+ }
+ _api_keys[key_id] = api_key
+ return _v1_response(api_key, 201)
+
+
+def _get_api_keys():
+ return _v1_response({"item": list(_api_keys.values())})
+
+
+def _get_api_key(key_id):
+ key = _api_keys.get(key_id)
+ if not key:
+ return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
+ return _v1_response(key)
+
+
+def _update_api_key(key_id, data):
+ key = _api_keys.get(key_id)
+ if not key:
+ return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(key, patch_ops)
+ key["lastUpdatedDate"] = _now_iso()
+ return _v1_response(key)
+
+
+def _delete_api_key(key_id):
+ if key_id not in _api_keys:
+ return _v1_error("NotFoundException", f"Invalid API Key identifier specified", 404)
+ _api_keys.pop(key_id, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Usage Plans ----
+
+def _create_usage_plan(data):
+ plan_id = _new_id()[:8]
+ plan = {
+ "id": plan_id,
+ "name": data.get("name", ""),
+ "description": data.get("description", ""),
+ "apiStages": data.get("apiStages", []),
+ "throttle": data.get("throttle", {}),
+ "quota": data.get("quota", {}),
+ "tags": data.get("tags", {}),
+ }
+ _usage_plans[plan_id] = plan
+ _usage_plan_keys[plan_id] = {}
+ return _v1_response(plan, 201)
+
+
+def _get_usage_plans():
+ return _v1_response({"item": list(_usage_plans.values())})
+
+
+def _get_usage_plan(plan_id):
+ plan = _usage_plans.get(plan_id)
+ if not plan:
+ return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_response(plan)
+
+
+def _update_usage_plan(plan_id, data):
+ plan = _usage_plans.get(plan_id)
+ if not plan:
+ return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ patch_ops = data.get("patchOperations", [])
+ _apply_patch(plan, patch_ops)
+ return _v1_response(plan)
+
+
+def _delete_usage_plan(plan_id):
+ if plan_id not in _usage_plans:
+ return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ _usage_plans.pop(plan_id, None)
+ _usage_plan_keys.pop(plan_id, None)
+ return 202, {}, b""
+
+
+def _create_usage_plan_key(plan_id, data):
+ if plan_id not in _usage_plans:
+ return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ key_id = data.get("keyId", "")
+ key_type = data.get("keyType", "API_KEY")
+ plan_key = {
+ "id": key_id,
+ "type": key_type,
+ "name": _api_keys.get(key_id, {}).get("name", ""),
+ "value": _api_keys.get(key_id, {}).get("value", ""),
+ }
+ _usage_plan_keys.setdefault(plan_id, {})[key_id] = plan_key
+ return _v1_response(plan_key, 201)
+
+
+def _get_usage_plan_keys(plan_id):
+ if plan_id not in _usage_plans:
+ return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ return _v1_response({"item": list(_usage_plan_keys.get(plan_id, {}).values())})
+
+
+def _delete_usage_plan_key(plan_id, key_id):
+ if plan_id not in _usage_plans:
+ return _v1_error("NotFoundException", f"Invalid Usage Plan identifier specified", 404)
+ _usage_plan_keys.get(plan_id, {}).pop(key_id, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Domain Names ----
+
+def _create_domain_name(data):
+ domain_name = data.get("domainName", "")
+ if not domain_name:
+ return _v1_error("BadRequestException", "Domain name is required", 400)
+ dn = {
+ "domainName": domain_name,
+ "certificateName": data.get("certificateName", ""),
+ "certificateArn": data.get("certificateArn", ""),
+ "distributionDomainName": f"{domain_name}.cloudfront.net",
+ "regionalDomainName": f"{domain_name}.execute-api.{REGION}.amazonaws.com",
+ "regionalHostedZoneId": "Z1UJRXOUMOOFQ8",
+ "endpointConfiguration": data.get("endpointConfiguration", {"types": ["REGIONAL"]}),
+ "tags": data.get("tags", {}),
+ }
+ _domain_names[domain_name] = dn
+ _base_path_mappings[domain_name] = {}
+ return _v1_response(dn, 201)
+
+
+def _get_domain_names():
+ return _v1_response({"item": list(_domain_names.values())})
+
+
+def _get_domain_name(domain_name):
+ dn = _domain_names.get(domain_name)
+ if not dn:
+ return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ return _v1_response(dn)
+
+
+def _delete_domain_name(domain_name):
+ if domain_name not in _domain_names:
+ return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ _domain_names.pop(domain_name, None)
+ _base_path_mappings.pop(domain_name, None)
+ return 202, {}, b""
+
+
+def _create_base_path_mapping(domain_name, data):
+ if domain_name not in _domain_names:
+ return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ base_path = data.get("basePath", "(none)")
+ mapping = {
+ "basePath": base_path,
+ "restApiId": data.get("restApiId", ""),
+ "stage": data.get("stage", ""),
+ }
+ _base_path_mappings.setdefault(domain_name, {})[base_path] = mapping
+ return _v1_response(mapping, 201)
+
+
+def _get_base_path_mappings(domain_name):
+ if domain_name not in _domain_names:
+ return _v1_error("NotFoundException", f"Invalid domain name identifier specified", 404)
+ return _v1_response({"item": list(_base_path_mappings.get(domain_name, {}).values())})
+
+
+def _get_base_path_mapping(domain_name, base_path):
+ mapping = _base_path_mappings.get(domain_name, {}).get(base_path)
+ if not mapping:
+ return _v1_error("NotFoundException", f"Invalid base path mapping identifier specified", 404)
+ return _v1_response(mapping)
+
+
+def _delete_base_path_mapping(domain_name, base_path):
+ _base_path_mappings.get(domain_name, {}).pop(base_path, None)
+ return 202, {}, b""
+
+
+# ---- Control plane: Tags ----
+
+def _get_v1_tags(resource_arn):
+ tags = _v1_tags.get(resource_arn, {})
+ return _v1_response({"tags": tags})
+
+
+def _tag_v1_resource(resource_arn, data):
+ tags = data.get("tags", {})
+ _v1_tags.setdefault(resource_arn, {}).update(tags)
+ return 204, {}, b""
+
+
+def _untag_v1_resource(resource_arn, tag_keys):
+ existing = _v1_tags.get(resource_arn, {})
+ for key in tag_keys:
+ existing.pop(key, None)
+ return 204, {}, b""
diff --git a/tests/conftest.py b/tests/conftest.py
index 02956bb2..6f7e6b4e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -121,6 +121,10 @@ def athena():
def apigw():
return make_client("apigatewayv2")
[email protected](scope="session")
+def apigw_v1():
+ return make_client("apigateway")
+
@pytest.fixture(scope="session")
def sfn_sync():
"""SFN client for StartSyncExecution — forces same endpoint (boto3 normally prefixes sync-)."""
diff --git a/tests/test_services.py b/tests/test_services.py
index f8751133..4c60fb5e 100644
--- a/tests/test_services.py
+++ b/tests/test_services.py
@@ -6371,3 +6371,950 @@ def test_sfn_integration_multi_service_pipeline(sfn, sqs, ddb):
msgs = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1)
assert len(msgs.get("Messages", [])) == 1
assert msgs["Messages"][0]["Body"] == "order-42"
+
+
+# ========== API Gateway REST API v1 ==========
+
+
+def test_apigwv1_create_rest_api(apigw_v1):
+ """CreateRestApi returns id, name, and createdDate as datetime."""
+ import datetime
+ resp = apigw_v1.create_rest_api(name="v1-create-test")
+ assert "id" in resp
+ assert resp["name"] == "v1-create-test"
+ assert "createdDate" in resp
+ assert isinstance(resp["createdDate"], datetime.datetime), "createdDate must be a datetime, not a float"
+ apigw_v1.delete_rest_api(restApiId=resp["id"])
+
+
+def test_apigwv1_get_rest_api(apigw_v1):
+ """GetRestApi returns the created API."""
+ api_id = apigw_v1.create_rest_api(name="v1-get-test")["id"]
+ resp = apigw_v1.get_rest_api(restApiId=api_id)
+ assert resp["id"] == api_id
+ assert resp["name"] == "v1-get-test"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_get_rest_apis(apigw_v1):
+ """GetRestApis returns item list containing created APIs."""
+ id1 = apigw_v1.create_rest_api(name="v1-list-a")["id"]
+ id2 = apigw_v1.create_rest_api(name="v1-list-b")["id"]
+ resp = apigw_v1.get_rest_apis()
+ ids = [a["id"] for a in resp["items"]]
+ assert id1 in ids
+ assert id2 in ids
+ apigw_v1.delete_rest_api(restApiId=id1)
+ apigw_v1.delete_rest_api(restApiId=id2)
+
+
+def test_apigwv1_update_rest_api(apigw_v1):
+ """UpdateRestApi (PATCH) modifies the API name."""
+ api_id = apigw_v1.create_rest_api(name="v1-update-before")["id"]
+ apigw_v1.update_rest_api(
+ restApiId=api_id,
+ patchOperations=[{"op": "replace", "path": "/name", "value": "v1-update-after"}],
+ )
+ resp = apigw_v1.get_rest_api(restApiId=api_id)
+ assert resp["name"] == "v1-update-after"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_rest_api(apigw_v1):
+ """DeleteRestApi removes the API; subsequent GetRestApi raises."""
+ api_id = apigw_v1.create_rest_api(name="v1-delete-test")["id"]
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_rest_api(restApiId=api_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+def test_apigwv1_create_resource(apigw_v1):
+ """CreateResource creates a child resource with computed path."""
+ api_id = apigw_v1.create_rest_api(name="v1-resource-create")["id"]
+ # Get root resource id
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resp = apigw_v1.create_resource(
+ restApiId=api_id,
+ parentId=root["id"],
+ pathPart="users",
+ )
+ assert resp["pathPart"] == "users"
+ assert resp["path"] == "/users"
+ assert "id" in resp
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_get_resources(apigw_v1):
+ """GetResources returns the root resource plus any created children."""
+ api_id = apigw_v1.create_rest_api(name="v1-get-resources")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.create_resource(restApiId=api_id, parentId=root["id"], pathPart="items")
+ resources = apigw_v1.get_resources(restApiId=api_id)["items"]
+ paths = [r["path"] for r in resources]
+ assert "/" in paths
+ assert "/items" in paths
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_put_get_method(apigw_v1):
+ """PutMethod creates a method; GetMethod returns it."""
+ api_id = apigw_v1.create_rest_api(name="v1-method-test")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="ping",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ authorizationType="NONE",
+ )
+ resp = apigw_v1.get_method(restApiId=api_id, resourceId=resource_id, httpMethod="GET")
+ assert resp["httpMethod"] == "GET"
+ assert resp["authorizationType"] == "NONE"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_put_integration(apigw_v1):
+ """PutIntegration sets AWS_PROXY integration on a method."""
+ api_id = apigw_v1.create_rest_api(name="v1-integration-test")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="ping",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE",
+ )
+ resp = apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri="arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFunc/invocations",
+ )
+ assert resp["type"] == "AWS_PROXY"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_put_method_response(apigw_v1):
+ """PutMethodResponse sets a 200 method response."""
+ api_id = apigw_v1.create_rest_api(name="v1-method-response-test")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="things",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE",
+ )
+ resp = apigw_v1.put_method_response(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ statusCode="200",
+ )
+ assert resp["statusCode"] == "200"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_put_integration_response(apigw_v1):
+ """PutIntegrationResponse sets a 200 integration response."""
+ api_id = apigw_v1.create_rest_api(name="v1-int-response-test")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="things",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="MOCK",
+ integrationHttpMethod="POST",
+ uri="",
+ )
+ resp = apigw_v1.put_integration_response(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ statusCode="200",
+ selectionPattern="",
+ )
+ assert resp["statusCode"] == "200"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_create_deployment(apigw_v1):
+ """CreateDeployment returns a deployment with id and createdDate."""
+ api_id = apigw_v1.create_rest_api(name="v1-deployment-test")["id"]
+ resp = apigw_v1.create_deployment(restApiId=api_id, description="initial deployment")
+ assert "id" in resp
+ assert "createdDate" in resp
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_create_stage(apigw_v1):
+ """CreateStage creates a named stage linked to a deployment."""
+ api_id = apigw_v1.create_rest_api(name="v1-stage-test")["id"]
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ resp = apigw_v1.create_stage(
+ restApiId=api_id,
+ stageName="prod",
+ deploymentId=dep_id,
+ )
+ assert resp["stageName"] == "prod"
+ assert resp["deploymentId"] == dep_id
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_update_stage(apigw_v1):
+ """UpdateStage (PATCH) updates stage variables."""
+ api_id = apigw_v1.create_rest_api(name="v1-stage-update")["id"]
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="dev", deploymentId=dep_id)
+ apigw_v1.update_stage(
+ restApiId=api_id,
+ stageName="dev",
+ patchOperations=[{"op": "replace", "path": "/variables/myVar", "value": "myVal"}],
+ )
+ resp = apigw_v1.get_stage(restApiId=api_id, stageName="dev")
+ assert resp["variables"]["myVar"] == "myVal"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_authorizer_crud(apigw_v1):
+ """Authorizer full lifecycle: create, get, update (patch), delete."""
+ api_id = apigw_v1.create_rest_api(name="v1-auth-crud")["id"]
+ auth = apigw_v1.create_authorizer(
+ restApiId=api_id,
+ name="my-auth",
+ type="TOKEN",
+ authorizerUri="arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:auth/invocations",
+ identitySource="method.request.header.Authorization",
+ )
+ auth_id = auth["id"]
+ assert auth["name"] == "my-auth"
+
+ got = apigw_v1.get_authorizer(restApiId=api_id, authorizerId=auth_id)
+ assert got["id"] == auth_id
+
+ apigw_v1.update_authorizer(
+ restApiId=api_id,
+ authorizerId=auth_id,
+ patchOperations=[{"op": "replace", "path": "/name", "value": "renamed-auth"}],
+ )
+ got2 = apigw_v1.get_authorizer(restApiId=api_id, authorizerId=auth_id)
+ assert got2["name"] == "renamed-auth"
+
+ listed = apigw_v1.get_authorizers(restApiId=api_id)["items"]
+ assert any(a["id"] == auth_id for a in listed)
+
+ apigw_v1.delete_authorizer(restApiId=api_id, authorizerId=auth_id)
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_authorizer(restApiId=api_id, authorizerId=auth_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_model_crud(apigw_v1):
+ """CreateModel, GetModel, DeleteModel lifecycle."""
+ api_id = apigw_v1.create_rest_api(name="v1-model-crud")["id"]
+ resp = apigw_v1.create_model(
+ restApiId=api_id,
+ name="MyModel",
+ contentType="application/json",
+ schema='{"type": "object"}',
+ )
+ assert resp["name"] == "MyModel"
+
+ got = apigw_v1.get_model(restApiId=api_id, modelName="MyModel")
+ assert got["name"] == "MyModel"
+
+ listed = apigw_v1.get_models(restApiId=api_id)["items"]
+ assert any(m["name"] == "MyModel" for m in listed)
+
+ apigw_v1.delete_model(restApiId=api_id, modelName="MyModel")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_model(restApiId=api_id, modelName="MyModel")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_tags(apigw_v1):
+ """TagResource, GetTags, UntagResource."""
+ api_id = apigw_v1.create_rest_api(name="v1-tags-test")["id"]
+ arn = f"arn:aws:apigateway:us-east-1::/restapis/{api_id}"
+
+ apigw_v1.tag_resource(resourceArn=arn, tags={"env": "test", "team": "platform"})
+ resp = apigw_v1.get_tags(resourceArn=arn)
+ assert resp["tags"]["env"] == "test"
+ assert resp["tags"]["team"] == "platform"
+
+ apigw_v1.untag_resource(resourceArn=arn, tagKeys=["env"])
+ resp2 = apigw_v1.get_tags(resourceArn=arn)
+ assert "env" not in resp2["tags"]
+ assert resp2["tags"]["team"] == "platform"
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_apikey_crud(apigw_v1):
+ """ApiKey full lifecycle: create, get, delete."""
+ resp = apigw_v1.create_api_key(name="v1-test-key", enabled=True)
+ key_id = resp["id"]
+ assert resp["name"] == "v1-test-key"
+ assert "value" in resp
+
+ got = apigw_v1.get_api_key(apiKey=key_id, includeValue=True)
+ assert got["id"] == key_id
+
+ listed = apigw_v1.get_api_keys()["items"]
+ assert any(k["id"] == key_id for k in listed)
+
+ apigw_v1.delete_api_key(apiKey=key_id)
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_api_key(apiKey=key_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+def test_apigwv1_usage_plan_crud(apigw_v1):
+ """UsagePlan full lifecycle: create, get, delete."""
+ resp = apigw_v1.create_usage_plan(
+ name="v1-plan",
+ throttle={"rateLimit": 100, "burstLimit": 200},
+ quota={"limit": 10000, "period": "MONTH"},
+ )
+ plan_id = resp["id"]
+ assert resp["name"] == "v1-plan"
+
+ got = apigw_v1.get_usage_plan(usagePlanId=plan_id)
+ assert got["id"] == plan_id
+
+ listed = apigw_v1.get_usage_plans()["items"]
+ assert any(p["id"] == plan_id for p in listed)
+
+ apigw_v1.delete_usage_plan(usagePlanId=plan_id)
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_usage_plan(usagePlanId=plan_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+# ---- Data plane tests ----
+
+def test_apigwv1_execute_lambda_proxy(apigw_v1, lam):
+ """End-to-end: create API + resource + method + integration + deploy + invoke Lambda."""
+ import uuid as _uuid
+ import urllib.request as _urlreq
+
+ fname = f"intg-v1-proxy-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"import json\n"
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 200, 'body': 'pong'}\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-exec-{fname}")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="ping",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/ping"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+ body = resp.read()
+ assert body == b"pong"
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_path_params(apigw_v1, lam):
+ """Path parameter {userId} is passed correctly in event['pathParameters']."""
+ import uuid as _uuid
+ import urllib.request as _urlreq
+
+ fname = f"intg-v1-params-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"import json\n"
+ b"def handler(event, context):\n"
+ b" uid = (event.get('pathParameters') or {}).get('userId', 'missing')\n"
+ b" return {'statusCode': 200, 'body': uid}\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-params-{fname}")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ users_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="users",
+ )["id"]
+ user_id_res = apigw_v1.create_resource(
+ restApiId=api_id, parentId=users_id, pathPart="{userId}",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=user_id_res, httpMethod="GET", authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=user_id_res,
+ httpMethod="GET",
+ type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="v1", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/v1/users/alice123"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+ assert resp.read() == b"alice123"
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_mock_integration(apigw_v1):
+ """MOCK integration returns fixed JSON from integration response template."""
+ import urllib.request as _urlreq
+
+ api_id = apigw_v1.create_rest_api(name="v1-mock-test")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(
+ restApiId=api_id, parentId=root["id"], pathPart="mock",
+ )["id"]
+ apigw_v1.put_method(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE",
+ )
+ apigw_v1.put_integration(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ type="MOCK",
+ integrationHttpMethod="GET",
+ uri="",
+ requestTemplates={"application/json": '{"statusCode": 200}'},
+ )
+ apigw_v1.put_method_response(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", statusCode="200",
+ )
+ apigw_v1.put_integration_response(
+ restApiId=api_id,
+ resourceId=resource_id,
+ httpMethod="GET",
+ statusCode="200",
+ selectionPattern="",
+ responseTemplates={"application/json": '{"mocked": true}'},
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/mock"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+ body = json.loads(resp.read())
+ assert body["mocked"] is True
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_execute_missing_resource_404(apigw_v1):
+ """Request to non-existent path returns 404 with AWS-style message."""
+ import urllib.request as _urlreq
+ import urllib.error as _urlerr
+
+ api_id = apigw_v1.create_rest_api(name="v1-missing-resource")["id"]
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/nonexistent"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ try:
+ _urlreq.urlopen(req)
+ assert False, "Expected 404"
+ except _urlerr.HTTPError as e:
+ assert e.code == 404
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_no_conflict_with_v2(apigw_v1, apigw, lam):
+ """v1 and v2 APIs can coexist; execute-api routes them independently."""
+ import uuid as _uuid
+ import urllib.request as _urlreq
+
+ # Create v1 Lambda
+ fname_v1 = f"intg-coexist-v1-{_uuid.uuid4().hex[:8]}"
+ code_v1 = b"def handler(event, context):\n return {'statusCode': 200, 'body': 'v1-response'}\n"
+ buf_v1 = io.BytesIO()
+ with zipfile.ZipFile(buf_v1, "w") as zf:
+ zf.writestr("index.py", code_v1)
+ lam.create_function(
+ FunctionName=fname_v1,
+ Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf_v1.getvalue()},
+ )
+
+ # Create v2 Lambda
+ fname_v2 = f"intg-coexist-v2-{_uuid.uuid4().hex[:8]}"
+ code_v2 = b"def handler(event, context):\n return {'statusCode': 200, 'body': 'v2-response'}\n"
+ buf_v2 = io.BytesIO()
+ with zipfile.ZipFile(buf_v2, "w") as zf:
+ zf.writestr("index.py", code_v2)
+ lam.create_function(
+ FunctionName=fname_v2,
+ Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler",
+ Code={"ZipFile": buf_v2.getvalue()},
+ )
+
+ # Set up v1 API
+ v1_api_id = apigw_v1.create_rest_api(name="coexist-v1")["id"]
+ root = next(r for r in apigw_v1.get_resources(restApiId=v1_api_id)["items"] if r["path"] == "/")
+ res_id = apigw_v1.create_resource(restApiId=v1_api_id, parentId=root["id"], pathPart="hit")["id"]
+ apigw_v1.put_method(restApiId=v1_api_id, resourceId=res_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_integration(
+ restApiId=v1_api_id, resourceId=res_id, httpMethod="GET",
+ type="AWS_PROXY", integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname_v1}/invocations",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=v1_api_id)["id"]
+ apigw_v1.create_stage(restApiId=v1_api_id, stageName="s", deploymentId=dep_id)
+
+ # Set up v2 API
+ v2_api_id = apigw.create_api(Name="coexist-v2", ProtocolType="HTTP")["ApiId"]
+ int_id = apigw.create_integration(
+ ApiId=v2_api_id, IntegrationType="AWS_PROXY",
+ IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname_v2}",
+ PayloadFormatVersion="2.0",
+ )["IntegrationId"]
+ apigw.create_route(ApiId=v2_api_id, RouteKey="GET /hit", Target=f"integrations/{int_id}")
+ apigw.create_stage(ApiId=v2_api_id, StageName="$default")
+
+ # Invoke v1
+ url_v1 = f"http://{v1_api_id}.execute-api.localhost:{_EXECUTE_PORT}/s/hit"
+ req_v1 = _urlreq.Request(url_v1, method="GET")
+ req_v1.add_header("Host", f"{v1_api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp_v1 = _urlreq.urlopen(req_v1)
+ assert resp_v1.status == 200
+ assert resp_v1.read() == b"v1-response"
+
+ # Invoke v2
+ url_v2 = f"http://{v2_api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/hit"
+ req_v2 = _urlreq.Request(url_v2, method="GET")
+ req_v2.add_header("Host", f"{v2_api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp_v2 = _urlreq.urlopen(req_v2)
+ assert resp_v2.status == 200
+ assert resp_v2.read() == b"v2-response"
+
+ # Cleanup
+ apigw_v1.delete_rest_api(restApiId=v1_api_id)
+ apigw.delete_api(ApiId=v2_api_id)
+ lam.delete_function(FunctionName=fname_v1)
+ lam.delete_function(FunctionName=fname_v2)
+
+
+# ---- Additional coverage: update, delete sub-resources, execute-api edge cases ----
+
+
+def test_apigwv1_update_rest_api_name(apigw_v1):
+ """UpdateRestApi renames the API via patchOperations."""
+ api_id = apigw_v1.create_rest_api(name="v1-update-name-before")["id"]
+ apigw_v1.update_rest_api(
+ restApiId=api_id,
+ patchOperations=[{"op": "replace", "path": "/name", "value": "v1-update-name-after"}],
+ )
+ assert apigw_v1.get_rest_api(restApiId=api_id)["name"] == "v1-update-name-after"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_resource(apigw_v1):
+ """DeleteResource removes a resource; subsequent GetResource raises 404."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-resource")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ child_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="todel")["id"]
+ apigw_v1.delete_resource(restApiId=api_id, resourceId=child_id)
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_resource(restApiId=api_id, resourceId=child_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_method(apigw_v1):
+ """DeleteMethod removes method; GetMethod raises 404 after."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-method")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.delete_method(restApiId=api_id, resourceId=root_id, httpMethod="GET")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_method(restApiId=api_id, resourceId=root_id, httpMethod="GET")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_integration(apigw_v1):
+ """DeleteIntegration removes integration; GetIntegration raises 404 after."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-integration")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET", type="MOCK")
+ apigw_v1.delete_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_method_response(apigw_v1):
+ """DeleteMethodResponse removes the method response entry."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-mresp")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_method_response(restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200")
+ apigw_v1.delete_method_response(restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_method_response(restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_integration_response(apigw_v1):
+ """DeleteIntegrationResponse removes the integration response entry."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-iresp")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET", type="MOCK")
+ apigw_v1.put_integration_response(
+ restApiId=api_id, resourceId=root_id, httpMethod="GET",
+ statusCode="200", selectionPattern="",
+ )
+ apigw_v1.delete_integration_response(restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_integration_response(restApiId=api_id, resourceId=root_id, httpMethod="GET", statusCode="200")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_deployment(apigw_v1):
+ """DeleteDeployment removes deployment; GetDeployment raises 404 after."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-deploy")["id"]
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.delete_deployment(restApiId=api_id, deploymentId=dep_id)
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_deployment(restApiId=api_id, deploymentId=dep_id)
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_delete_stage(apigw_v1):
+ """DeleteStage removes stage; GetStage raises 404 after."""
+ api_id = apigw_v1.create_rest_api(name="v1-del-stage")["id"]
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="todel", deploymentId=dep_id)
+ apigw_v1.delete_stage(restApiId=api_id, stageName="todel")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_stage(restApiId=api_id, stageName="todel")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_update_api_key(apigw_v1):
+ """UpdateApiKey updates name and sets lastUpdatedDate."""
+ import datetime
+ key_id = apigw_v1.create_api_key(name="v1-key-update-before")["id"]
+ resp = apigw_v1.update_api_key(
+ apiKey=key_id,
+ patchOperations=[{"op": "replace", "path": "/name", "value": "v1-key-update-after"}],
+ )
+ assert resp["name"] == "v1-key-update-after"
+ assert isinstance(resp["lastUpdatedDate"], datetime.datetime)
+ apigw_v1.delete_api_key(apiKey=key_id)
+
+
+def test_apigwv1_update_usage_plan(apigw_v1):
+ """UpdateUsagePlan updates name via patchOperations."""
+ plan_id = apigw_v1.create_usage_plan(name="v1-plan-update-before")["id"]
+ resp = apigw_v1.update_usage_plan(
+ usagePlanId=plan_id,
+ patchOperations=[{"op": "replace", "path": "/name", "value": "v1-plan-update-after"}],
+ )
+ assert resp["name"] == "v1-plan-update-after"
+ apigw_v1.delete_usage_plan(usagePlanId=plan_id)
+
+
+def test_apigwv1_deployment_api_summary(apigw_v1):
+ """CreateDeployment apiSummary reflects methods configured on resources."""
+ api_id = apigw_v1.create_rest_api(name="v1-api-summary")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET", type="MOCK")
+ dep = apigw_v1.create_deployment(restApiId=api_id)
+ assert "/" in dep.get("apiSummary", {}), "apiSummary must include root resource path"
+ assert "GET" in dep["apiSummary"]["/"], "apiSummary must include configured HTTP method"
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_domain_name_crud(apigw_v1):
+ """DomainName create, get, list, delete lifecycle."""
+ resp = apigw_v1.create_domain_name(
+ domainName="api.example.com",
+ endpointConfiguration={"types": ["REGIONAL"]},
+ )
+ assert resp["domainName"] == "api.example.com"
+ got = apigw_v1.get_domain_name(domainName="api.example.com")
+ assert got["domainName"] == "api.example.com"
+ listed = apigw_v1.get_domain_names()["items"]
+ assert any(d["domainName"] == "api.example.com" for d in listed)
+ apigw_v1.delete_domain_name(domainName="api.example.com")
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_domain_name(domainName="api.example.com")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+
+def test_apigwv1_base_path_mapping_crud(apigw_v1):
+ """BasePathMapping create, get, list, delete lifecycle."""
+ apigw_v1.create_domain_name(domainName="bpm.example.com")
+ api_id = apigw_v1.create_rest_api(name="v1-bpm-api")["id"]
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="prod", deploymentId=dep_id)
+
+ mapping = apigw_v1.create_base_path_mapping(
+ domainName="bpm.example.com", basePath="v1",
+ restApiId=api_id, stage="prod",
+ )
+ assert mapping["basePath"] == "v1"
+ assert mapping["restApiId"] == api_id
+
+ got = apigw_v1.get_base_path_mapping(domainName="bpm.example.com", basePath="v1")
+ assert got["basePath"] == "v1"
+
+ listed = apigw_v1.get_base_path_mappings(domainName="bpm.example.com")["items"]
+ assert any(m["basePath"] == "v1" for m in listed)
+
+ apigw_v1.delete_base_path_mapping(domainName="bpm.example.com", basePath="v1")
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ apigw_v1.delete_domain_name(domainName="bpm.example.com")
+
+
+def test_apigwv1_execute_missing_stage_404(apigw_v1):
+ """execute-api returns 404 when stage does not exist."""
+ import urllib.request as _urlreq
+ import urllib.error as _urlerr
+ api_id = apigw_v1.create_rest_api(name="v1-no-stage")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET", type="MOCK")
+ apigw_v1.create_deployment(restApiId=api_id)
+ # Do NOT create a stage — request to a nonexistent stage should 404
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/nonexistent/"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ with pytest.raises(_urlerr.HTTPError) as exc:
+ _urlreq.urlopen(req)
+ assert exc.value.code == 404
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_execute_missing_method_405(apigw_v1):
+ """execute-api returns 405 when resource exists but method is not configured."""
+ import urllib.request as _urlreq
+ import urllib.error as _urlerr
+ api_id = apigw_v1.create_rest_api(name="v1-no-method")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="noop")["id"]
+ # PUT method for POST only — GET not configured
+ apigw_v1.put_method(restApiId=api_id, resourceId=resource_id, httpMethod="POST", authorizationType="NONE")
+ apigw_v1.put_integration(restApiId=api_id, resourceId=resource_id, httpMethod="POST", type="MOCK")
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/noop"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ with pytest.raises(_urlerr.HTTPError) as exc:
+ _urlreq.urlopen(req)
+ assert exc.value.code == 405
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_execute_lambda_arn_uri(apigw_v1, lam):
+ """execute-api Lambda proxy works with plain arn:aws:lambda ARN as integration URI."""
+ import uuid as _uuid
+ import urllib.request as _urlreq
+
+ fname = f"v1-arn-uri-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"import json\n"
+ b"def handler(event, context):\n"
+ b" return {'statusCode': 200, 'body': 'arn-ok'}\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname, Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-arn-{fname}")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="hit")["id"]
+ apigw_v1.put_method(restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE")
+ # Use plain arn:aws:lambda ARN (not apigateway URI form)
+ apigw_v1.put_integration(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/hit"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.status == 200
+ assert resp.read() == b"arn-ok"
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_lambda_requestcontext(apigw_v1, lam):
+ """execute-api Lambda event includes required requestContext fields."""
+ import uuid as _uuid
+ import urllib.request as _urlreq
+
+ fname = f"v1-reqctx-{_uuid.uuid4().hex[:8]}"
+ code = (
+ b"import json\n"
+ b"def handler(event, context):\n"
+ b" ctx = event.get('requestContext', {})\n"
+ b" body = json.dumps({\n"
+ b" 'stage': ctx.get('stage'),\n"
+ b" 'httpMethod': ctx.get('httpMethod'),\n"
+ b" 'apiId': ctx.get('apiId'),\n"
+ b" 'has_requestTime': 'requestTime' in ctx,\n"
+ b" 'has_requestTimeEpoch': 'requestTimeEpoch' in ctx,\n"
+ b" 'has_protocol': 'protocol' in ctx,\n"
+ b" 'has_path': 'path' in ctx,\n"
+ b" 'has_mvh': 'multiValueHeaders' in event,\n"
+ b" })\n"
+ b" return {'statusCode': 200, 'body': body}\n"
+ )
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ lam.create_function(
+ FunctionName=fname, Runtime="python3.9",
+ Role="arn:aws:iam::000000000000:role/test-role",
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},
+ )
+
+ api_id = apigw_v1.create_rest_api(name=f"v1-ctx-{fname}")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="ctx")["id"]
+ apigw_v1.put_method(restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_integration(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", type="AWS_PROXY",
+ integrationHttpMethod="POST",
+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:{fname}/invocations",
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="prod", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/ctx"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ data = json.loads(resp.read())
+ assert data["stage"] == "prod"
+ assert data["httpMethod"] == "GET"
+ assert data["apiId"] == api_id
+ assert data["has_requestTime"] is True
+ assert data["has_requestTimeEpoch"] is True
+ assert data["has_protocol"] is True
+ assert data["has_path"] is True
+ assert data["has_mvh"] is True
+
+ apigw_v1.delete_rest_api(restApiId=api_id)
+ lam.delete_function(FunctionName=fname)
+
+
+def test_apigwv1_execute_mock_response_parameters(apigw_v1):
+ """MOCK integration responseParameters are applied as HTTP response headers."""
+ import urllib.request as _urlreq
+ api_id = apigw_v1.create_rest_api(name="v1-mock-params")["id"]
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ resource_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="rp")["id"]
+ apigw_v1.put_method(restApiId=api_id, resourceId=resource_id, httpMethod="GET", authorizationType="NONE")
+ apigw_v1.put_method_response(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET", statusCode="200",
+ responseParameters={"method.response.header.X-Custom-Header": False},
+ )
+ apigw_v1.put_integration(restApiId=api_id, resourceId=resource_id, httpMethod="GET", type="MOCK",
+ requestTemplates={"application/json": '{"statusCode": 200}'})
+ apigw_v1.put_integration_response(
+ restApiId=api_id, resourceId=resource_id, httpMethod="GET",
+ statusCode="200", selectionPattern="",
+ responseTemplates={"application/json": '{"ok": true}'},
+ responseParameters={"method.response.header.X-Custom-Header": "'myvalue'"},
+ )
+ dep_id = apigw_v1.create_deployment(restApiId=api_id)["id"]
+ apigw_v1.create_stage(restApiId=api_id, stageName="test", deploymentId=dep_id)
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/test/rp"
+ req = _urlreq.Request(url, method="GET")
+ req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
+ resp = _urlreq.urlopen(req)
+ assert resp.headers.get("X-Custom-Header") == "myvalue"
+ apigw_v1.delete_rest_api(restApiId=api_id)