Search code examples
spring-bootswaggeropenapispringdoc

How can I add custom json object to Openapi spec generated by SpringBoot SpringDoc?


My springboot project generates openapi spec using SpringDoc. I want to add a json object to the generated spec

{
    "api-definition": {
      "priority": 1,
      "owner: "jack"
    }
}

so that the generated spec file looks like

{"openapi":"3.0.1",

  ................

  ................

  "api-definition": {
      "priority": 1,
      "owner: "jack"
  }
}

Can someone please help.


Solution

  • I was able to do this by creating an OpenApiCustomiser bean.

    @Configuration
    public class OpenApiConfig {
    
    @Bean
    public OpenApiCustomiser customise() {
        return openApi -> {
            try {
                openApi.setExtensions(vendorExtensions());
            } catch (JsonProcessingException e) {
                log.error("bad json, should never happen");
            }
        };
    }
    
    private static ObjectMapper mapper = new ObjectMapper();
    
    private Map<String, Object> vendorExtensions() throws JsonProcessingException {
        MapType type = mapper.getTypeFactory().constructMapType(
                Map.class, String.class, Object.class);
        Map<String, Object> stringObjectMap = new HashMap<>();
    
        stringObjectMap.put("api-definition",
                mapper.readValue(readFile("api-definition.json"), type));
        return stringObjectMap;
    }
    
    //To read file from resources folder
    private String readFile(String fileName) {
        ClassLoader classLoader = getClass().getClassLoader();
        try {
            return Files.readString(Path.of(classLoader.getResource(fileName).getFile()));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
        return null;
    }
    
    }
    

    api-definition.json looks like below

    { 
      "priority": 1,
      "owner: "jack"
    }