Warm tip: This article is reproduced from serverfault.com, please click

How to handle OptionalInt parameters as integers in Swagger?

发布于 2020-12-02 09:23:34

I'm trying to get an OpenAPI definition for an existing Jersey project.

I have many methods taking OptionalInt parameters, for example :

public Response listAgents(@Auth AuthenticatedUser auth,
            @QueryParam("count") OptionalInt count, @QueryParam("start") OptionalInt start)

Swagger detects these parameters as objects (which is false):

      parameters:
      - name: count
        in: query
        schema:
          type: object
          properties:
            empty:
              type: boolean
            present:
              type: boolean
            asInt:
              type: integer
              format: int32

Is there a way to configure Swagger to handle OptionalInt type as Integer type, whitout rewriting each and every method with @Parameter(schema = @Schema(implementation = Integer.class)) annotation on each parameter ?

Questioner
Bastien Durel
Viewed
0
Bastien Durel 2020-12-03 17:15:04

I found a solution :

In the configuration file I put a model converter

modelConverterClasses: 
- fr.data.openapi.WaPropertyConverter

in which I defined the schema to handle OptionalInt parameters :

import io.swagger.v3.core.converter.ModelConverter;

public class WaPropertyConverter implements ModelConverter {
    @Override
    public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) {
        if (type.getType() instanceof SimpleType) {
            SimpleType type_ = (SimpleType) type.getType();
            if (type_.isTypeOrSubTypeOf(OptionalInt.class))
                return optionalIntSchema();

        }
        if (chain.hasNext()) {
            return chain.next().resolve(type, context, chain);
        } else {
            return null;
        }
    }

    protected Schema<?> optionalIntSchema() {
        Schema<Integer> s = new Schema<Integer>();
        s.setType("integer");
        s.format("int32");
        return s;
    }
}

With this I get the correct schema for all my OptionalInt's

      - name: count
        in: query
        schema:
          type: integer
          format: int32