简体   繁体   中英

Java Spring Boot: Swagger GET List in the Request

I am trying to setup a GET request in Java Spring Boot Swagger, with a list of ProductIds in the request. How can I edit the code below for this?

@GET
@Path("/product/{customerId}/{productIds}")
@ApiOperation(
        value = "Get Products",
        response = ProductResponse.class,
        responseContainer = "List"
)
List<ProductResponse> getProductData(
        @ApiParam(value = "customerId", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "productIds", required = true) @PathParam("productIds") List<Long> productIds
);

Result: with CustomerId 7 and ProductIds (2,3)

404 Not Found

http://localhost:50111/product-domain/api/product/7/2%2C3

Update: if I use RequestParam for ProductIds, how would I input this in swagger body? Note: any solution will work, (don't necessarily need to use RequestParam)

   @RequestParam(value="productIds", required=true) List<Long> productIds

在此处输入图像描述

In my opinion you should not use PathVariable but RequestParam (preferably RequestBody) in this case.

In case of using RequestParam it is should looks like:

@Path("/product/{customerId}")
List<ProductResponse> getProductData(
        @ApiParam(value = "customerId", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "productIds", required = true) @RequestParam("productIds") List<Long> productIds
);

than your url will look like: http://localhost:50111/product-domain/api/product/7?productIds=2,3

In case of using RequestBody it is should looks like:

@Path("/product/{customerId}")
List<ProductResponse> getProductData(
        @ApiParam(value = "customerId", required = true) @PathParam("customerId") long customerId,
        @ApiParam(value = "productIds", required = true) @RequestBody("productIds") List<Long> productIds
);

than your url will look like: http://localhost:50111/product-domain/api/product/7 and your http request body should contains: [2, 3]

Why I advise against using @PathParam in this case?

  • Url length has length limit (around 2048 characters) - so if You try pass long list in future it is can be a problem
  • Url needs to "normalize"/"escape" special characters, what makes url less readable for human, which is the essence of using PathParam

BTW: Consider using PathVariable instead of PathParam - because PathVariable is from Spring, but PathParam is from JAX-RS and I assume you want to use Spring Boot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM