Search code examples
swaggerspringfox

How add a custom field to the generated Swagger json from SpringFox?


I'm trying to add the field externalDocs to the generated Json from Springfox:

"externalDocs": {
    "description": "find more info here",
    "url": "https://swagger.io/about"
},

Reading the SpringFox documentation, I understand that I need to create a plugin to extends the SpringFox funcionalities and add this field. I tried:

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1002)
@Slf4j
public class ExternalDocSwaggerConfiguration implements ApiListingBuilderPlugin {

    @Override
    public void apply(final ApiListingContext apiListingContext) {

        ObjectVendorExtension ext = new ObjectVendorExtension("externalDocs");
        ext.addProperty(new StringVendorExtension("description", "Link externo"));
        ext.addProperty(new StringVendorExtension("url", "https://swagger.io/about"));
        apiListingContext.apiListingBuilder().extensions(
            Collections.singletonList(ext)); // extensions does not exist
    }

    @Override
    public boolean supports(final DocumentationType documentationType) {
        return true;
    }
}

I was expecting to add the extension, as showed here with the OperationBuilderPlugin, but there is no extensions method on the apiListingBuilder.

So, how could I add this tag on the root of the generated Swagger Json using SpringFox?


Solution

  • The version 2.7.0 added this feature.

    To add this field externalDocs, you can use the extensions method from the Docket:

    @Bean
    public Docket customImplementation() {
    
        ObjectVendorExtension ext = new ObjectVendorExtension("externalDocs");
        ext.addProperty(new StringVendorExtension("description", "Link externo"));
        ext.addProperty(new StringVendorExtension("url", "https://swagger.io/about"));
    
        return new Docket(DocumentationType.SWAGGER_2)
                .extensions(Collections.singletonList(ext))
                .apiInfo(apiInfo())
                .securitySchemes(newArrayList(apiKey()))
                .pathMapping("/api")
                .securityContexts(newArrayList(securityContext())).select()
                .apis(getPackages())
                .paths(PathSelectors.any())
                .build();
    }