Skip to content

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

Support API Gateway documentation parts in CloudFormation (#1160)

robert-pitt-foodhub31c10b8e03da
diff --git a/README.md b/README.md
index 6b7bc760..29396cb4 100644
--- a/README.md
+++ b/README.md
@@ -430,7 +430,7 @@ subnet = ec2.create_subnet(
| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |
| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); `$default` stage served from the URL root (no stage segment in the path); per-API `corsConfiguration` applied to preflights + dispatched responses; request parameter mapping for HTTP_PROXY (`append/overwrite/remove` for headers/querystring plus `overwrite:path`) with context variables including `$context.authorizer.jwt.claims`; JWT data-plane authorization for HTTP routes (issuer/audience/time/scope checks) and claim propagation to integrations; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; JWT/Lambda authorizer CRUD; pin `apiId` across runs with the `ms-custom-id` tag |
-| **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` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
+| **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, CreateDocumentationPart, GetDocumentationPart, GetDocumentationParts, UpdateDocumentationPart, DeleteDocumentationPart, 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` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; qualified-alias integration URIs (`arn:...:function:<name>:<alias>`) resolve to the alias's target version; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence; pin `id` across runs with the `ms-custom-id` tag |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, SetSubnets, SetIpAddressType, SetSecurityGroups, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 29 actions; CMK specs: RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), Edwards25519 (`ECC_NIST_EDWARDS25519` — pure Ed25519 via `ED25519_SHA_512` with `MessageType=RAW`; `ED25519_PH_SHA_512` advertised in `SigningAlgorithms` but returns `UnsupportedOperationException` until Ed25519ph lands), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption, incl. asymmetric data key pairs (`KeyPairSpec` adds RSA_3072); alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
| **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, CreateFunction, DeleteFunction, DescribeFunction, GetFunction, ListFunctions, PublishFunction, UpdateFunction, **KeyValueStore (mgmt)**: CreateKeyValueStore, DescribeKeyValueStore, ListKeyValueStores, UpdateKeyValueStore, DeleteKeyValueStore, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin config round-trip; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; **CloudFront Functions** are API stubs (in-memory code + DEVELOPMENT/LIVE ETags for Terraform `aws_cloudfront_function`) with `KeyValueStoreAssociations` round-tripped — no `TestFunction`, no viewer-request JS execution at the edge; `UpdateFunction` clears the emulated LIVE stage until `PublishFunction` runs again |
@@ -492,6 +492,7 @@ subnet = ec2.create_subnet(
| `AWS::ApiGateway::Stage` | Stage name | — |
| `AWS::ApiGateway::DomainName` | Domain name | DistributionDomainName, DistributionHostedZoneId, DomainNameArn, RegionalDomainName, RegionalHostedZoneId |
| `AWS::ApiGateway::GatewayResponse` | Response ID | Id |
+| `AWS::ApiGateway::DocumentationPart` | Documentation part ID | — |
| `AWS::AppConfig::Application` | Application ID | ApplicationId |
| `AWS::AppSync::GraphQLApi` | API ID | Arn, GraphQLUrl, ApiId |
| `AWS::AppSync::DataSource` | DataSource name | DataSourceArn |
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 6fbf348d..692ab482 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -43,6 +43,11 @@ Control plane endpoints implemented:
GET /restapis/{id}/models — GetModels
GET /restapis/{id}/models/{modelName} — GetModel
DELETE /restapis/{id}/models/{modelName} — DeleteModel
+ POST /restapis/{id}/documentation/parts — CreateDocumentationPart
+ GET /restapis/{id}/documentation/parts — GetDocumentationParts
+ GET /restapis/{id}/documentation/parts/{partId} — GetDocumentationPart
+ PATCH /restapis/{id}/documentation/parts/{partId} — UpdateDocumentationPart
+ DELETE /restapis/{id}/documentation/parts/{partId} — DeleteDocumentationPart
PUT /restapis/{id}/gatewayresponses/{responseType} — PutGatewayResponse
GET /restapis/{id}/gatewayresponses — GetGatewayResponses
GET /restapis/{id}/gatewayresponses/{responseType} — GetGatewayResponse
@@ -120,6 +125,7 @@ _base_path_mappings = AccountScopedDict() # domain_name -> {base_path -> BasePa
_v1_tags = AccountScopedDict() # resource_arn -> {key -> value}
_account_settings = AccountScopedDict() # singleton per account: stores fields set via UpdateAccount
_gateway_responses = AccountScopedDict() # rest_api_id -> {response_type -> customized GatewayResponse}
+_documentation_parts = AccountScopedDict() # rest_api_id -> {part_id -> DocumentationPart}
_GATEWAY_RESPONSE_TYPES = (
@@ -170,6 +176,23 @@ _DEFAULT_GATEWAY_RESPONSE_STATUS_CODES = {
_DEFAULT_GATEWAY_RESPONSE_TEMPLATE = '{"message":$context.error.messageString}'
+_DOCUMENTATION_LOCATION_TYPES = frozenset(
+ {
+ "API",
+ "AUTHORIZER",
+ "MODEL",
+ "RESOURCE",
+ "METHOD",
+ "PATH_PARAMETER",
+ "QUERY_PARAMETER",
+ "REQUEST_HEADER",
+ "REQUEST_BODY",
+ "RESPONSE",
+ "RESPONSE_HEADER",
+ "RESPONSE_BODY",
+ }
+)
+
# ---- Helpers ----
@@ -648,6 +671,7 @@ def get_state():
"v1_tags": copy.deepcopy(_v1_tags),
"account_settings": copy.deepcopy(_account_settings),
"gateway_responses": copy.deepcopy(_gateway_responses),
+ "documentation_parts": copy.deepcopy(_documentation_parts),
}
@@ -726,6 +750,7 @@ def load_persisted_state(data):
_v1_tags.update(data.get("v1_tags", {}))
_account_settings.update(data.get("account_settings", {}))
_gateway_responses.update(data.get("gateway_responses", {}))
+ _documentation_parts.update(data.get("documentation_parts", {}))
_backfill_tag_region_map(_rest_apis, _rest_api_regions, _region_from_rest_api_record)
_backfill_tag_region_map(_api_keys, _api_key_regions, _region_from_api_key_record)
_backfill_tag_region_map(_usage_plans, _usage_plan_regions, _region_from_usage_plan_record)
@@ -752,6 +777,7 @@ def reset():
_v1_tags.clear()
_account_settings.clear()
_gateway_responses.clear()
+ _documentation_parts.clear()
# ---- Control plane router ----
@@ -1022,6 +1048,22 @@ async def handle_request(method, path, headers, body, query_params):
if method == "DELETE":
return _delete_model(api_id, model_name)
+ # /restapis/{id}/documentation/parts[/{partId}]
+ elif sub == "documentation" and len(parts) > 3 and parts[3] == "parts":
+ part_id = parts[4] if len(parts) > 4 else None
+ if part_id is None:
+ if method == "POST":
+ return _create_documentation_part(api_id, data)
+ if method == "GET":
+ return _get_documentation_parts(api_id, query_params)
+ else:
+ if method == "GET":
+ return _get_documentation_part(api_id, part_id)
+ if method == "PATCH":
+ return _update_documentation_part(api_id, part_id, data)
+ if method == "DELETE":
+ return _delete_documentation_part(api_id, part_id)
+
# /restapis/{id}/gatewayresponses[/{responseType}]
elif sub == "gatewayresponses":
response_type = parts[3] if len(parts) > 3 else None
@@ -1393,6 +1435,7 @@ def _create_rest_api(data):
_authorizers_v1[api_id] = {}
_models[api_id] = {}
_gateway_responses[api_id] = {}
+ _documentation_parts[api_id] = {}
# Create root resource "/"
root_id = _new_id()[:8]
@@ -1440,6 +1483,7 @@ def _delete_rest_api(api_id):
_authorizers_v1.pop(api_id, None)
_models.pop(api_id, None)
_gateway_responses.pop(api_id, None)
+ _documentation_parts.pop(api_id, None)
_v1_tags.pop(_rest_api_arn(api_id), None)
return 202, {}, b""
@@ -2017,6 +2061,112 @@ def _delete_model(api_id, model_name):
return 202, {}, b""
+# ---- Control plane: Documentation Parts ----
+
+def _validate_documentation_api(api_id):
+ if api_id not in _rest_apis:
+ return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
+ return None
+
+
+def _create_documentation_part(api_id, data):
+ error = _validate_documentation_api(api_id)
+ if error is not None:
+ return error
+
+ location = dict(data.get("location") or {})
+ location_type = location.get("type")
+ if location_type not in _DOCUMENTATION_LOCATION_TYPES:
+ return _v1_error(
+ "BadRequestException",
+ "Invalid documentation part location type specified",
+ 400,
+ )
+ if data.get("properties") is None:
+ return _v1_error(
+ "BadRequestException",
+ "Documentation part properties must be specified",
+ 400,
+ )
+
+ part_id = _new_id()
+ part = {
+ "id": part_id,
+ "location": location,
+ "properties": data["properties"],
+ }
+ _documentation_parts.setdefault(api_id, {})[part_id] = part
+ return _v1_response(part, 201)
+
+
+def _get_documentation_part(api_id, part_id):
+ error = _validate_documentation_api(api_id)
+ if error is not None:
+ return error
+ part = _documentation_parts.get(api_id, {}).get(part_id)
+ if part is None:
+ return _v1_error(
+ "NotFoundException",
+ "Invalid DocumentationPart identifier specified",
+ 404,
+ )
+ return _v1_response(part)
+
+
+def _get_documentation_parts(api_id, query_params):
+ error = _validate_documentation_api(api_id)
+ if error is not None:
+ return error
+
+ parts = list(_documentation_parts.get(api_id, {}).values())
+ location_type = _qp(query_params, "type")
+ name_query = _qp(query_params, "name")
+ path = _qp(query_params, "path")
+ location_status = _qp(query_params, "locationStatus")
+ if location_type:
+ parts = [part for part in parts if part["location"].get("type") == location_type]
+ if name_query:
+ parts = [part for part in parts if name_query in part["location"].get("name", "")]
+ if path:
+ parts = [part for part in parts if part["location"].get("path") == path]
+ # Stored parts are documented by definition. API Gateway also synthesizes
+ # undocumented API entities for this filter; MiniStack has no need to
+ # materialize those placeholder records.
+ if location_status == "UNDOCUMENTED":
+ parts = []
+ return _v1_paginated_response(parts, query_params)
+
+
+def _update_documentation_part(api_id, part_id, data):
+ error = _validate_documentation_api(api_id)
+ if error is not None:
+ return error
+ part = _documentation_parts.get(api_id, {}).get(part_id)
+ if part is None:
+ return _v1_error(
+ "NotFoundException",
+ "Invalid DocumentationPart identifier specified",
+ 404,
+ )
+ _apply_patch(part, data.get("patchOperations", []))
+ return _v1_response(part)
+
+
+def _delete_documentation_part(api_id, part_id):
+ error = _validate_documentation_api(api_id)
+ if error is not None:
+ return error
+ parts = _documentation_parts.get(api_id, {})
+ if part_id not in parts:
+ return _v1_error(
+ "NotFoundException",
+ "Invalid DocumentationPart identifier specified",
+ 404,
+ )
+ parts.pop(part_id, None)
+ return 202, {}, b""
+
+
# ---- Control plane: Gateway Responses ----
def _default_gateway_response(response_type):
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 2d1d3a40..c136376d 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -2270,6 +2270,71 @@ def _apigw_gateway_response_delete(physical_id, props):
_apigw_v1._delete_gateway_response(api_id, response_type)
+# --- API Gateway DocumentationPart ---
+
+def _apigw_documentation_part_create(logical_id, props, stack_name):
+ """Provision an ``AWS::ApiGateway::DocumentationPart``."""
+ api_id = props.get("RestApiId", "")
+ cfn_location = props.get("Location", {})
+ location_keys = {
+ "Type": "type",
+ "Path": "path",
+ "Method": "method",
+ "StatusCode": "statusCode",
+ "Name": "name",
+ }
+ data = {
+ "location": {
+ api_key: cfn_location[cfn_key]
+ for cfn_key, api_key in location_keys.items()
+ if cfn_key in cfn_location
+ },
+ "properties": props.get("Properties"),
+ }
+ status, _headers, body = _apigw_v1._create_documentation_part(api_id, data)
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::DocumentationPart create failed: {body!r}")
+
+ part = json.loads(body) if isinstance(body, (bytes, bytearray)) else json.loads(body)
+ part_id = part.get("id", "")
+ return part_id, {"Id": part_id, "DocumentationPartId": part_id}
+
+
+def _apigw_documentation_part_update(physical_id, old_props, new_props, stack_name):
+ # RestApiId and Location require replacement in the AWS CFN resource
+ # specification; Properties is mutable in place.
+ if any(new_props.get(key) != old_props.get(key) for key in ("RestApiId", "Location")):
+ new_id, attrs = _apigw_documentation_part_create(physical_id, new_props, stack_name)
+ _apigw_documentation_part_delete(physical_id, old_props)
+ return new_id, attrs
+
+ if new_props.get("Properties") != old_props.get("Properties"):
+ api_id = new_props.get("RestApiId", "")
+ data = {
+ "patchOperations": [
+ {
+ "op": "replace",
+ "path": "/properties",
+ "value": new_props.get("Properties", ""),
+ },
+ ],
+ }
+ status, _headers, body = _apigw_v1._update_documentation_part(
+ api_id, physical_id, data,
+ )
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::DocumentationPart update failed: {body!r}")
+ return physical_id, {"Id": physical_id, "DocumentationPartId": physical_id}
+
+
+def _apigw_documentation_part_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ parts = _apigw_v1._documentation_parts.get(api_id, {})
+ # Keep rollback and parent-first cleanup idempotent.
+ if physical_id in parts:
+ _apigw_v1._delete_documentation_part(api_id, physical_id)
+
+
# --- Lambda EventSourceMapping ---
def _lambda_esm_create(logical_id, props, stack_name):
@@ -4995,6 +5060,11 @@ _RESOURCE_HANDLERS = {
"update": _apigw_gateway_response_update,
"delete": _apigw_gateway_response_delete,
},
+ "AWS::ApiGateway::DocumentationPart": {
+ "create": _apigw_documentation_part_create,
+ "update": _apigw_documentation_part_update,
+ "delete": _apigw_documentation_part_delete,
+ },
"AWS::Lambda::EventSourceMapping": {"create": _lambda_esm_create, "update": _lambda_esm_update, "delete": _lambda_esm_delete},
"AWS::Lambda::EventInvokeConfig": {
"create": _lambda_event_invoke_config_create,
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index dd614dc8..ca9e0966 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -204,6 +204,86 @@ def test_apigwv1_gateway_response_state_survives_persistence_roundtrip():
service.reset()
+def test_apigwv1_documentation_part_crud(apigw_v1):
+ """Documentation parts create, list, update, and delete through the SDK."""
+ api_id = apigw_v1.create_rest_api(name="v1-documentation-part-test")["id"]
+ created = apigw_v1.create_documentation_part(
+ restApiId=api_id,
+ location={"type": "RESOURCE", "path": "/pets"},
+ properties='{"description":"Pet operations"}',
+ )
+ part_id = created["id"]
+
+ try:
+ fetched = apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=part_id,
+ )
+ assert fetched["location"] == {"type": "RESOURCE", "path": "/pets"}
+ assert fetched["properties"] == '{"description":"Pet operations"}'
+
+ listed = apigw_v1.get_documentation_parts(
+ restApiId=api_id,
+ type="RESOURCE",
+ path="/pets",
+ )["items"]
+ assert [part["id"] for part in listed] == [part_id]
+
+ updated = apigw_v1.update_documentation_part(
+ restApiId=api_id,
+ documentationPartId=part_id,
+ patchOperations=[
+ {
+ "op": "replace",
+ "path": "/properties",
+ "value": '{"description":"Updated pet operations"}',
+ },
+ ],
+ )
+ assert updated["id"] == part_id
+ assert updated["properties"] == '{"description":"Updated pet operations"}'
+
+ apigw_v1.delete_documentation_part(
+ restApiId=api_id,
+ documentationPartId=part_id,
+ )
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=part_id,
+ )
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_documentation_part_state_survives_persistence_roundtrip():
+ from ministack.services import apigateway_v1 as service
+
+ service.reset()
+ try:
+ _status, _headers, body = service._create_rest_api({"name": "persist-doc-part"})
+ api_id = json.loads(body)["id"]
+ _status, _headers, body = service._create_documentation_part(
+ api_id,
+ {
+ "location": {"type": "API"},
+ "properties": '{"description":"Persisted"}',
+ },
+ )
+ part_id = json.loads(body)["id"]
+
+ snapshot = service.get_state()
+ service.reset()
+ service.load_persisted_state(snapshot)
+
+ restored = service._documentation_parts[api_id][part_id]
+ assert restored["location"] == {"type": "API"}
+ assert restored["properties"] == '{"description":"Persisted"}'
+ finally:
+ service.reset()
+
+
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"]
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index eec6382e..59ae2730 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -4681,6 +4681,113 @@ def test_cfn_apigateway_gateway_response_lifecycle(cfn, apigw_v1):
apigw_v1.delete_rest_api(restApiId=api_id)
+def test_cfn_apigateway_documentation_part_lifecycle(cfn, apigw_v1):
+ """DocumentationPart supports create, update, replacement, Ref, and delete.
+
+ Regression for #1159: the resource type previously failed stack creation
+ with ``Unsupported resource type: AWS::ApiGateway::DocumentationPart``.
+ """
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-documentation-part-{suffix}"
+ api_id = apigw_v1.create_rest_api(name=f"documentation-part-{suffix}")["id"]
+ stack_deleted = False
+
+ def template(location, description):
+ return {
+ "Resources": {
+ "DocumentationPart": {
+ "Type": "AWS::ApiGateway::DocumentationPart",
+ "Properties": {
+ "RestApiId": api_id,
+ "Location": location,
+ "Properties": json.dumps({"description": description}),
+ },
+ },
+ },
+ "Outputs": {
+ "DocumentationPartId": {"Value": {"Ref": "DocumentationPart"}},
+ },
+ }
+
+ def physical_id():
+ detail = cfn.describe_stack_resource(
+ StackName=stack_name,
+ LogicalResourceId="DocumentationPart",
+ )["StackResourceDetail"]
+ return detail["PhysicalResourceId"]
+
+ try:
+ cfn.create_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template({"Type": "API"}, "Created")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ created_id = physical_id()
+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack.get("Outputs", [])}
+ assert outputs["DocumentationPartId"] == created_id
+ created = apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=created_id,
+ )
+ assert created["location"] == {"type": "API"}
+ assert json.loads(created["properties"])["description"] == "Created"
+
+ # Properties updates in place.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template({"Type": "API"}, "Updated")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert physical_id() == created_id
+ updated = apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=created_id,
+ )
+ assert json.loads(updated["properties"])["description"] == "Updated"
+
+ # Location is immutable and replaces the documentation part.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(
+ template({"Type": "RESOURCE", "Path": "/pets"}, "Replacement")
+ ),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ replacement_id = physical_id()
+ assert replacement_id != created_id
+ with pytest.raises(ClientError):
+ apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=created_id,
+ )
+ replacement = apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=replacement_id,
+ )
+ assert replacement["location"] == {"type": "RESOURCE", "path": "/pets"}
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ stack_deleted = True
+ with pytest.raises(ClientError):
+ apigw_v1.get_documentation_part(
+ restApiId=api_id,
+ documentationPartId=replacement_id,
+ )
+ finally:
+ if not stack_deleted:
+ try:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ except ClientError:
+ pass
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
# ---------------------------------------------------------------------------
# ApiGatewayV1 Integration with OpenAPI spec parsing
# ---------------------------------------------------------------------------