swagger-api / swagger-core

Examples and server integrations for generating the Swagger API Specification, which enables easy access to your REST API
http://swagger.io
Apache License 2.0
7.36k stars 2.17k forks source link

BUG @Schema#implementation not processed on properties when generating open api 3.1.0 #4679

Open Lorenzo-Bracci opened 1 month ago

Lorenzo-Bracci commented 1 month ago

Problem

When generating OpenAPI 3.1.0 spec the @Schema#implementation value on a property is ignored.

Expected behaviour

@Schema#implementation is considered also in OAS3.1

Reproducer

The issues is reproduced in the following test (note that the test is successful if the model resolvers generate OAS3.0.1 instead):

    @Test(description = "Shows that @Schema#implementation is not propagated from property when using oas 3.1.0")
    public void testModelWithCustomSchemaImplementationInPropertyForOas31() {

        String expectedYaml = "ModelWithCustomSchemaImplementationInProperty:\n" +
                "  type: object\n" +
                "  properties:\n" +
                "    exampleField:\n" +
                // the expected type is int rather than string as we override the type with @Schema(implementation = Integer.class)
                "      type: integer\n" +
                "      format: int32\n";

        Map<String, io.swagger.v3.oas.models.media.Schema> stringSchemaMap = ModelConverters.getInstance(true).readAll(ModelWithCustomSchemaImplementationInProperty.class);

        // fails as @Schema#implementation is not processed and therefore the original property type is used (String)
        SerializationMatchers.assertEqualsToYaml31(stringSchemaMap, expectedYaml);
    }

    static class ModelWithCustomSchemaImplementationInProperty {

        @Schema(implementation = Integer.class)
        private String exampleField;

        public String getExampleField() {
            return exampleField;
        }

        public void setExampleField(String exampleField) {
            this.exampleField = exampleField;
        }

    }

Investigation with proposed solution

Looking at the ModelResolver code, it seems that @Schema annotation is not propagated when attempting to resolve a model for a property (it is excluded from context annotations in ModelResolver#682). There is an attempt to reconcile this information at ModelResolver#719 (through AnnotationsUtils.getSchemaFromAnnotation). Information from @Schema#implementation is not used here but I imagine that it is necessary to use this information before attempting to resolve the model rather than after as it seems central in the model resolution process. Therefore I wonder if possibly overriding the AnnotatedType#type used for context.resolve in ModelResolver#716 could be a proper solution for the issue?