Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigateway): select request models by content type and default (#5530)
Andre Kuraite77710d32dca
diff --git a/compatibility-tests/sdk-test-python/tests/test_apigateway_request_models.py b/compatibility-tests/sdk-test-python/tests/test_apigateway_request_models.pynew file mode 100644index 0000000000..dab0bfbcea--- /dev/null+++ b/compatibility-tests/sdk-test-python/tests/test_apigateway_request_models.py@@ -0,0 +1,65 @@+"""Request model selection verified against live API Gateway on 2026-10-12."""++import http.client+import json+import uuid+from contextlib import closing+from urllib.parse import urlsplit++import boto3+import pytest++[email protected]("models", [+ {"application/json": "Named"},+ {"$default": "Fallback"},+ {"application/json": "Named", "$default": "Fallback"},+])+def test_request_model_content_type_selection(aws_config, endpoint_url, models):+ with closing(boto3.client("apigateway", **aws_config)) as api:+ api_id = api.create_rest_api(name="models-" + uuid.uuid4().hex)["id"]+ try:+ root = next(resource["id"] for resource in+ api.get_resources(restApiId=api_id)["items"]+ if resource["path"] == "/")+ validator = api.create_request_validator(+ restApiId=api_id, name="body", validateRequestBody=True,+ validateRequestParameters=False)["id"]+ for name, field in [("Named", "name"), ("Fallback", "fallback")]:+ api.create_model(+ restApiId=api_id, name=name, contentType="application/json",+ schema=json.dumps({"type": "object", "required": [field],+ "properties": {field: {"type": "string"}}}))+ method = {"restApiId": api_id, "resourceId": root, "httpMethod": "POST"}+ api.put_method(**method, authorizationType="NONE",+ requestValidatorId=validator, requestModels=models)+ api.put_method_response(**method, statusCode="200")+ api.put_integration(+ **method, type="MOCK", passthroughBehavior="WHEN_NO_MATCH",+ requestTemplates={ct: '{"statusCode":200}' for ct in+ ["application/json", "text/plain"]})+ api.put_integration_response(+ **method, statusCode="200",+ responseTemplates={"application/json": '{"ok":true}'})+ api.create_deployment(restApiId=api_id, stageName="test")++ endpoint = urlsplit(endpoint_url)+ connection_type = (http.client.HTTPSConnection if endpoint.scheme == "https"+ else http.client.HTTPConnection)+ for content_type in ["application/json", "text/plain",+ "application/json; charset=utf-8", None]:+ normalized = (content_type or "application/json").split(";")[0]+ model = models.get(normalized, models.get("$default"))+ required = {"Named": "name", "Fallback": "fallback"}.get(model)+ for payload in [{}, {"name": "ok"}, {"fallback": "ok"}]:+ headers = {"Content-Type": content_type} if content_type else {}+ # http.client preserves an absent Content-Type on a POST.+ with closing(connection_type(endpoint.netloc, timeout=10)) as conn:+ conn.request("POST", f"/execute-api/{api_id}/test/",+ body=json.dumps(payload), headers=headers)+ response = conn.getresponse()+ body = response.read()+ expected = 200 if required is None or required in payload else 400+ assert response.status == expected, (models, content_type, payload, body)+ finally:+ api.delete_rest_api(restApiId=api_id)diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex 38b489de75..c29fcbf519 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java@@ -1157,7 +1157,9 @@ public class ApiGatewayExecuteController {? headers.getMediaType().getType() + "/" + headers.getMediaType().getSubtype(): "application/json";String modelName = requestModels.get(contentType);- if (modelName == null) modelName = requestModels.get("application/json");+ if (modelName == null) {+ modelName = requestModels.get("$default");+ }if (modelName != null) {try {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRequestModelContentTypeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRequestModelContentTypeIntegrationTest.javanew file mode 100644index 0000000000..076aad2087--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRequestModelContentTypeIntegrationTest.java@@ -0,0 +1,115 @@+package io.github.hectorvent.floci.services.apigateway;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;++@QuarkusTest+class ApiGatewayRequestModelContentTypeIntegrationTest {++ private String apiId;+ private String resourceId;+ private String validatorId;++ @BeforeEach+ void createApi() {+ apiId = given().contentType(ContentType.JSON)+ .body(Map.of("name", "request-model-content-type"))+ .post("/restapis").then().statusCode(201).extract().path("id");+ resourceId = given().get("/restapis/" + apiId + "/resources")+ .then().statusCode(200).extract().path("item.find { it.path == '/' }.id");+ validatorId = given().contentType(ContentType.JSON)+ .body(Map.of("name", "body", "validateRequestBody", true,+ "validateRequestParameters", false))+ .post("/restapis/" + apiId + "/requestvalidators")+ .then().statusCode(201).extract().path("id");+ createModel("Named", "name");+ createModel("Fallback", "fallback");+ }++ @AfterEach+ void deleteApi() {+ if (apiId != null) {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ @Test+ void unmatchedContentTypeSkipsJsonModelValidation() {+ deploy(Map.of("application/json", "Named"));+ invoke("text/plain", "{\"unexpected\":true}", 200);+ invoke("text/plain", "not json", 200);+ invoke("application/json", "{\"unexpected\":true}", 400);+ invoke("application/json", "{\"name\":\"present\"}", 200);+ }++ @Test+ void defaultModelValidatesAnUnmatchedContentType() {+ deploy(Map.of("$default", "Fallback"));+ invoke("text/plain", "{\"unexpected\":true}", 400);+ invoke("text/plain", "{\"fallback\":\"present\"}", 200);+ invoke("application/json", "{\"unexpected\":true}", 400);+ invoke("application/json", "{\"fallback\":\"present\"}", 200);+ }++ @Test+ void exactModelTakesPrecedenceOverDefaultModel() {+ deploy(Map.of("application/json", "Named", "$default", "Fallback"));+ invoke("application/json", "{\"name\":\"present\"}", 200);+ invoke("application/json", "{\"fallback\":\"present\"}", 400);+ invoke("text/plain", "{\"name\":\"present\"}", 400);+ invoke("text/plain", "{\"fallback\":\"present\"}", 200);+ }++ @Test+ void mediaTypeParametersKeepTheMatchingModel() {+ deploy(Map.of("application/json", "Named"));+ invoke("application/json; charset=utf-8", "{\"unexpected\":true}", 400);+ invoke("application/json; charset=utf-8", "{\"name\":\"present\"}", 200);+ }++ private void createModel(String name, String requiredProperty) {+ String schema = """+ {"type":"object","required":["%s"],"properties":{"%s":{"type":"string"}}}+ """.formatted(requiredProperty, requiredProperty);+ given().contentType(ContentType.JSON)+ .body(Map.of("name", name, "contentType", "application/json", "schema", schema))+ .post("/restapis/" + apiId + "/models").then().statusCode(201);+ }++ private void deploy(Map<String, String> models) {+ String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST";+ given().contentType(ContentType.JSON)+ .body(Map.of("authorizationType", "NONE", "requestValidatorId", validatorId,+ "requestModels", models))+ .put(method).then().statusCode(201);+ given().contentType(ContentType.JSON)+ .body(Map.of("statusCode", "200"))+ .put(method + "/responses/200").then().statusCode(201);+ given().contentType(ContentType.JSON)+ .body(Map.of("type", "MOCK", "passthroughBehavior", "WHEN_NO_MATCH",+ "requestTemplates", Map.of(+ "application/json", "{\"statusCode\":200}",+ "text/plain", "{\"statusCode\":200}")))+ .put(method + "/integration").then().statusCode(201);+ given().contentType(ContentType.JSON)+ .body(Map.of("statusCode", "200",+ "responseTemplates", Map.of("application/json", "{\"ok\":true}")))+ .put(method + "/integration/responses/200").then().statusCode(201);+ given().contentType(ContentType.JSON)+ .body(Map.of("stageName", "test"))+ .post("/restapis/" + apiId + "/deployments").then().statusCode(201);+ }++ private void invoke(String contentType, String body, int expectedStatus) {+ given().contentType(contentType).body(body)+ .post("/execute-api/" + apiId + "/test/")+ .then().statusCode(expectedStatus);+ }+}