Skip to content

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

fix(apigateway): rank HTTP API routes by specificity, not insertion order (#1256)

Lukas Döllererf5f1fdc11294
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 74917750..8322bfc6 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -914,10 +914,39 @@ async def handle_execute(api_id, stage, path, method, headers, body, query_param
return response
+def _route_specificity(method: str, route_path: str) -> tuple:
+ """Rank a candidate route by how specifically it matches a request.
+
+ Real API Gateway always dispatches to the most specific matching route,
+ independent of the order in which routes were created. We approximate that
+ ordering with a tuple compared lexicographically (higher is more specific):
+
+ 1. Number of literal (non-parameter) path segments — an exact path beats
+ one with placeholders.
+ 2. Explicit method over ``ANY`` — ``POST /items`` beats ``ANY /items``.
+ 3. Non-greedy over greedy — a route without ``{proxy+}`` beats a catch-all.
+ """
+ segments = route_path.strip("/").split("/")
+ literal_segments = sum(
+ 1 for s in segments if not (s.startswith("{") and s.endswith("}"))
+ )
+ is_greedy = any(s == "{proxy+}" for s in segments)
+ return (literal_segments, 0 if method == "ANY" else 1, 0 if is_greedy else 1)
+
+
def _match_route(api_id, method, path):
- """Find the best matching route for method+path. $default route is the fallback."""
+ """Find the best matching route for method+path. $default route is the fallback.
+
+ All routes matching the request are ranked by specificity (see
+ ``_route_specificity``) and the most specific one wins, mirroring real API
+ Gateway. This matters when a dedicated route (e.g. ``POST /items``) and a
+ greedy catch-all (e.g. ``ANY /{proxy+}``) both match: the dedicated route
+ must win regardless of which was registered first.
+ """
routes = _routes.get(api_id, {})
- # First pass: look for a specific method+path match (skip $default)
+ # First pass: collect every specific method+path match (skip $default).
+ best_route = None
+ best_specificity = None
for route in routes.values():
key = route.get("routeKey", "")
if key == "$default":
@@ -926,7 +955,11 @@ def _match_route(api_id, method, path):
if len(parts) == 2:
r_method, r_path = parts
if (r_method == "ANY" or r_method == method) and _path_matches(r_path, path):
- return route
+ specificity = _route_specificity(r_method, r_path)
+ if best_specificity is None or specificity > best_specificity:
+ best_route, best_specificity = route, specificity
+ if best_route is not None:
+ return best_route
# Second pass: $default catch-all
for route in routes.values():
if route.get("routeKey") == "$default":
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index 080acd52..240c1e3e 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -198,6 +198,66 @@ def test_apigw_delete_route(apigw):
resp = apigw.get_routes(ApiId=api_id)
assert not any(r["RouteId"] == route_id for r in resp["Items"])
+def _make_api_with_routes(apigw_mod, route_keys):
+ """Register an in-process HTTP API with the given route keys, in order.
+
+ Uses the real ``_create_route`` path so the routes are built and inserted
+ exactly as a live request would, letting the tests exercise creation order.
+ """
+ api_id = apigw_mod.new_uuid()[:8]
+ apigw_mod._apis[api_id] = {"apiId": api_id, "protocolType": "HTTP"}
+ for route_key in route_keys:
+ apigw_mod._create_route(api_id, {"routeKey": route_key})
+ return api_id
+
+
[email protected]("proxy_first", [False, True])
+def test_apigw_match_route_prefers_specific_over_proxy(proxy_first):
+ """The exact route wins over an ``ANY /{proxy+}`` catch-all in either order.
+
+ Real API Gateway dispatches to the most specific matching route regardless
+ of creation order; ministack must not fall back to first-match-wins.
+ """
+ from ministack.services import apigateway as apigw_mod
+
+ exact = "POST /api/v1/sql/execute"
+ proxy = "ANY /{proxy+}"
+ keys = [proxy, exact] if proxy_first else [exact, proxy]
+ api_id = _make_api_with_routes(apigw_mod, keys)
+
+ route = apigw_mod._match_route(api_id, "POST", "/api/v1/sql/execute")
+ assert route is not None
+ assert route["routeKey"] == exact
+
+
[email protected]("proxy_first", [False, True])
+def test_apigw_match_route_falls_through_to_proxy(proxy_first):
+ """A path only the catch-all matches still resolves to ``ANY /{proxy+}``."""
+ from ministack.services import apigateway as apigw_mod
+
+ exact = "POST /api/v1/sql/execute"
+ proxy = "ANY /{proxy+}"
+ keys = [proxy, exact] if proxy_first else [exact, proxy]
+ api_id = _make_api_with_routes(apigw_mod, keys)
+
+ route = apigw_mod._match_route(api_id, "GET", "/something/else")
+ assert route is not None
+ assert route["routeKey"] == proxy
+
+
+def test_apigw_match_route_default_fallback():
+ """When no specific route matches, the $default route is the fallback."""
+ from ministack.services import apigateway as apigw_mod
+
+ api_id = _make_api_with_routes(
+ apigw_mod, ["POST /api/v1/sql/execute", "$default"]
+ )
+
+ route = apigw_mod._match_route(api_id, "GET", "/unmatched/path")
+ assert route is not None
+ assert route["routeKey"] == "$default"
+
+
def test_apigw_create_integration(apigw):
api_id = apigw.create_api(Name="integ-api", ProtocolType="HTTP")["ApiId"]
resp = apigw.create_integration(