fix(apigateway): paginate GetRestApis with limit and position (#9617)

This commit is contained in:
Matheus André authored and GitHub committed 2026-11-27 17:47:21 -04:00
1 parent 7db72767e3
commit 661808b384
19 files changed
+182 -25

No files matched your search

@@ -102,7 +102,7 @@ describe('API Gateway v1 — management plane', () => {
});
it('should list REST APIs including the created one', async () => {
const res = await gw.send(new GetRestApisCommand({}));
const res = await gw.send(new GetRestApisCommand({ limit: 500 }));
expect(res.items?.some(a => a.id === apiId)).toBe(true);
});
+6
View File
@@ -195,6 +195,12 @@ Tagged REST APIs, stages, API keys, usage plans and custom domain names are disc
[Resource Groups Tagging API](resource-groups-tagging.md), whose `TagResources` and `UntagResources`
write REST API, stage, API key, usage plan and custom domain name tags through to API Gateway.
### REST API Pagination
`GetRestApis` accepts `limit` and `position`, returns 25 APIs by default and caps pages at 500.
A nonterminal page includes `position`; the final page omits it. An unknown or blank `position`
is a `BadRequestException`.
### Base Path Mapping Pagination
`GetBasePathMappings` accepts `limit` and `position`, returns 25 mappings by default,
@@ -435,13 +435,14 @@ public class ApiGatewayController {
@GET
@Path("/restapis")
public Response getRestApis(@Context HttpHeaders headers) {
public Response getRestApis(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@QueryParam("limit") String limit, @QueryParam("position") String position) {
String region = regionResolver.resolveRegion(headers);
List<RestApi> apis = service.getRestApis(region);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("item");
apis.forEach(a -> items.add(toApiNode(region, a)));
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
// An empty query value binds as null, so presence is read from the URI.
String requestedPosition = position == null && uriInfo.getQueryParameters().containsKey("position")
? "" : position;
return pageResponse(service.getRestApiPage(region, pageLimit(limit), requestedPosition),
api -> toApiNode(region, api));
}
@GET
@@ -527,6 +527,14 @@ public class ApiGatewayService implements ResourceProvider, Resettable, PassedRo
return apiStore.scan(k -> k.startsWith(prefix));
}
/** AWS answers an explicitly empty {@code position}, and Floci a blank one, with a BadRequestException instead of the first page. */
public PaginatedResult<RestApi> getRestApiPage(String region, Integer limit, String position) {
if (position != null && position.isBlank()) {
throw new AwsException("BadRequestException", "Invalid position parameter", 400);
}
return pageById(getRestApis(region), RestApi::getId, limit, position);
}
public synchronized void deleteRestApi(String region, String apiId) {
getRestApi(region, apiId);
apiStore.delete(apiKey(region, apiId));
@@ -53,7 +53,7 @@ class ApiGatewayIntegrationTest {
@Test @Order(3)
void listRestApis() {
given()
.when().get("/restapis")
.when().get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.id", hasItem(apiId));
@@ -58,7 +58,7 @@ class ApiGatewayListRestApisConcurrentDeleteTest {
given()
.when()
.get("/restapis")
.get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.findAll { it.id == '" + apiId + "' }[0].rootResourceId", notNullValue())
@@ -322,7 +322,7 @@ class ApiGatewayOpenApiAnyMethodImportTest {
.body("__type", equalTo("BadRequestException"));
given()
.when().get("/restapis")
.when().get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.name", not(hasItem("FailedImportLeavesNothingAPI")));
@@ -1756,7 +1756,7 @@ class ApiGatewayOpenApiImportTest {
given().contentType(ContentType.JSON).queryParam("mode", "import").body(spec)
.post("/restapis").then().statusCode(400)
.body("message", containsString("Only one Authorizer or IAM authorization"));
given().get("/restapis").then().statusCode(200)
given().get("/restapis?limit=500").then().statusCode(200)
.body("item.find { it.name == 'MultiAuthAPI' }", nullValue());
}
@@ -1837,7 +1837,7 @@ class ApiGatewayOpenApiImportTest {
containsString("caching")));
given()
.when().get("/restapis")
.when().get("/restapis?limit=500")
.then().statusCode(200)
.body("item.name", not(hasItem(title)));
}
@@ -106,7 +106,7 @@ class ApiGatewayOpenApiParameterRefImportIntegrationTest {
.body("message", containsString("#/components/parameters/Missing"));
given()
.when().get("/restapis")
.when().get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.name", not(hasItem("MissingParameterRefAPI")));
@@ -232,7 +232,7 @@ class ApiGatewayOpenApiParameterRefImportIntegrationTest {
.body("message", containsString("#/components/parameters/Loop"));
given()
.when().get("/restapis")
.when().get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.name", not(hasItem("CyclicParameterRefAPI")));
@@ -88,7 +88,7 @@ class ApiGatewayOpenApiWarningsIntegrationTest {
}
private static List<String> apiIds() {
return given().get("/restapis").then().statusCode(200).extract().path("item.id");
return given().get("/restapis?limit=500").then().statusCode(200).extract().path("item.id");
}
@Test
@@ -0,0 +1,58 @@
package io.floci.aws.services.apigateway;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsCertificateManager;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.apigateway.model.RestApi;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ApiGatewayRestApiPageCapTest {
private static final String REGION = "us-east-1";
private ApiGatewayService service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
service = new ApiGatewayService(storageFactory, mock(EmulatorConfig.class),
mock(TlsCertificateManager.class), new RegionResolver(REGION, "000000000000"));
for (int i = 0; i < 501; i++) {
service.createRestApi(REGION, Map.of("name", "capped-" + i));
}
}
@Test
void aLimitAboveTheCapReturnsFiveHundredAndAUsablePosition() {
PaginatedResult<RestApi> first = service.getRestApiPage(REGION, 501, null);
assertEquals(500, first.items().size());
assertNotNull(first.nextToken());
PaginatedResult<RestApi> last = service.getRestApiPage(REGION, 501, first.nextToken());
assertEquals(1, last.items().size());
assertNull(last.nextToken());
}
@Test
void theLargestIntegerLimitIsCappedTheSameWay() {
PaginatedResult<RestApi> first = service.getRestApiPage(REGION, Integer.MAX_VALUE, null);
assertEquals(500, first.items().size());
assertNotNull(first.nextToken());
}
}
@@ -0,0 +1,77 @@
package io.floci.aws.services.apigateway;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.apache5.Apache5HttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
import software.amazon.awssdk.services.apigateway.model.BadRequestException;
import software.amazon.awssdk.services.apigateway.model.GetRestApisResponse;
import software.amazon.awssdk.services.apigateway.model.RestApi;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class ApiGatewayRestApiPagingIntegrationTest {
private ApiGatewayClient client() {
return AwsTestClients.create(ApiGatewayClient.builder(), "test", Region.US_EAST_1,
Apache5HttpClient.builder());
}
@Test
void getRestApisPagesWithLimitAndTheDefaultPageSize() {
try (ApiGatewayClient client = client()) {
Set<String> created = new HashSet<>();
try {
for (int i = 0; i < 26; i++) {
String name = "PagedApi" + i;
created.add(client.createRestApi(r -> r.name(name)).id());
}
GetRestApisResponse first = client.getRestApis(r -> r.limit(1));
assertEquals(1, first.items().size());
assertNotNull(first.position());
GetRestApisResponse second = client.getRestApis(r -> r.limit(1).position(first.position()));
assertEquals(1, second.items().size());
assertNotEquals(first.items().get(0).id(), second.items().get(0).id());
GetRestApisResponse defaultPage = client.getRestApis();
assertEquals(25, defaultPage.items().size());
assertNotNull(defaultPage.position());
List<String> seen = new ArrayList<>(defaultPage.items().stream().map(RestApi::id).toList());
String position = defaultPage.position();
while (position != null) {
String next = position;
GetRestApisResponse page = client.getRestApis(r -> r.position(next));
seen.addAll(page.items().stream().map(RestApi::id).toList());
position = page.position();
}
assertEquals(seen.size(), new HashSet<>(seen).size());
assertTrue(seen.containsAll(created));
assertThrows(BadRequestException.class,
() -> client.getRestApis(r -> r.limit(1).position("missing")));
given().queryParam("position", "").when().get("/restapis").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
given().queryParam("position", " ").when().get("/restapis").then().statusCode(400)
.body("__type", equalTo("BadRequestException"));
} finally {
created.forEach(id -> client.deleteRestApi(r -> r.restApiId(id)));
}
}
}
}
@@ -163,7 +163,7 @@ class ApiGatewayRestApiResponseFieldsTest {
given()
.when()
.get("/restapis")
.get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.findAll { it.id == '" + apiId + "' }.rootResourceId", everyItem(notNullValue()));
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.config.TlsCertificateManager;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
@@ -12,7 +13,9 @@ import io.floci.aws.services.apigateway.model.RestApi;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2OpenApiImporter;
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -92,7 +95,8 @@ class ApiGatewayRootResourceLookupTest {
api.setRootResourceId("root-id");
ApiGatewayService mockedService = mock(ApiGatewayService.class);
when(mockedService.getRestApis(REGION)).thenReturn(List.of(api));
when(mockedService.getRestApiPage(REGION, null, null))
.thenReturn(new PaginatedResult<>(List.of(api), null));
RegionResolver regionResolver = mock(RegionResolver.class);
HttpHeaders headers = mock(HttpHeaders.class);
when(regionResolver.resolveRegion(headers)).thenReturn(REGION);
@@ -101,7 +105,10 @@ class ApiGatewayRootResourceLookupTest {
mock(ApiGatewayV2Service.class), mock(ApiGatewayV2OpenApiImporter.class),
regionResolver, objectMapper, null);
Response response = controller.getRestApis(headers);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
Response response = controller.getRestApis(headers, uriInfo, null, null);
JsonNode body = objectMapper.readTree((String) response.getEntity());
assertEquals("root-id", body.path("item").get(0).path("rootResourceId").asText());
@@ -84,7 +84,7 @@ class ApiGatewayRestApiCfnImportRollbackIntegrationTest {
/** Of the REST APIs named {@link #API_NAME}, only the one created outside the stack is left, unchanged. */
private static void assertOnlyTheOutsideApiIsLeft(String outsideId) {
given().when().get("/restapis").then().statusCode(200)
given().when().get("/restapis?limit=500").then().statusCode(200)
.body("item.findAll { it.name == '" + API_NAME + "' }.id", contains(outsideId));
given().when().get("/restapis/" + outsideId).then().statusCode(200)
.body("description", equalTo("outside the stack"));
@@ -107,7 +107,7 @@ class ApiGatewayRestApiCfnUpdateIntegrationTest {
String apiId = created.get("ApiId");
assertEquals(apiId, updated.get("ApiId"));
assertEquals(created.get("ResourceId"), updated.get("ResourceId"));
given().when().get("/restapis").then().statusCode(200)
given().when().get("/restapis?limit=500").then().statusCode(200)
.body("item.findAll { it.name == '" + API_NAME + "' }.size()", equalTo(1));
given().when().get("/restapis/" + apiId).then().statusCode(200)
.body("description", equalTo("second"))
@@ -65,7 +65,7 @@ class SamRestApiAuthIntegrationTest {
given().contentType(ContentType.JSON).queryParam("mode", "import")
.body(document.toString()).post("/restapis").then().statusCode(400)
.body("message", containsString("Only one Authorizer or IAM authorization"));
given().get("/restapis").then().statusCode(200)
given().get("/restapis?limit=500").then().statusCode(200)
.body("item.find { it.name == '" + title + "' }", equalTo(null));
}
@@ -1137,7 +1137,7 @@ class SamTransformIntegrationTest {
String apiId = given()
.when()
.get("/restapis")
.get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.find { it.name == '" + apiName + "' }.name", equalTo(apiName))
@@ -1219,7 +1219,7 @@ class SamTransformIntegrationTest {
String apiId = given()
.when()
.get("/restapis")
.get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.find { it.name == '" + apiName + "' }.name", equalTo(apiName))
@@ -1291,7 +1291,7 @@ class SamTransformIntegrationTest {
// provisioner that never reads DefinitionBody at all cannot pass this test.
String apiId = given()
.when()
.get("/restapis")
.get("/restapis?limit=500")
.then()
.statusCode(200)
.body("item.name", hasItem(apiName))
@@ -150,7 +150,7 @@ class IamServingServiceEnforcementIntegrationTest {
given()
.header("Authorization", auth(ACCOUNT_ID, "apigateway"))
.when()
.get("/restapis")
.get("/restapis?limit=500")
.then()
.statusCode(200)
.body(not(containsString(apiName)));