How to annotate a Java List form-urlencoded parameter for Swagger?

Viewed 391

I have this API endpoint which expects one form-urlencoded array parameter. This is the relevant Java snippet:

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response addItems(@Parameter(description = "Items to add") @FormParam("items") List<Long> items) {
    return service.addItems(items);
}

I can't reach the endpoint from the generated Swagger UI because of the following error:

RESTEASY003870: Unable to extract parameter from http request: javax.ws.rs.FormParam(&quot;items&quot;) value is &#x27;1%2C2%2C3&#x27;

From what I read, Swagger is making this request:

curl -X 'POST' \
  'http://localhost:8080/items' \
  -H 'accept: */*' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'items=1,2,3'

It looks to me that the culprit is how Swagger serializes the array: Swagger sends this items=1,2,3 while RESTEasy expect this items=1&items=2&items=3.

I've already read the relevant Swagger documentation and tried every style/explode combination, including the ones that looks to have most sense for me (style = ParameterStyle.SIMPLE, explode = TRUE which by the way should be default behavior) with no luck.

So, how should I annotate this endpoint in order to Swagger to be able to invoke it?

1 Answers

I used https://github.com/quarkusio/quarkus-quickstarts/tree/main/openapi-swaggerui-quickstart and added your method to FruitResource

According to swagger documentation if you want to use form urlencoded

application/x-www-form-urlencoded is used to send simple ASCII text data as key=value pairs. The payload format is similar to query parameters.

at https://swagger.io/docs/specification/describing-request-body/, so it says use query params and I changed your function to


  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.APPLICATION_JSON)
  public Response addItems(
    @Parameter(description = "Items to add") @QueryParam(
      "items"
    ) List<Long> items
  ) {
    return service.addItems(items);
  }

and open the dev-ui

quarkus dev ui

As you can see UI is preventing to add wrong parameters, correct ui below

swagger call

and created curl command is working as expected.

curl -X 'POST' \
  'http://localhost:8080/fruits?items=1&items=2' \
  -H 'accept: */*' \
  -d ''

in case you want to test the code it is here.

Related