Skip to content

2. Setup

dzikoysk edited this page Jan 5, 2023 · 3 revisions

OpenAPI plugin for Javalin with Swagger UI:

Javalin.create(config -> {
    config.plugins.register(new OpenApiPlugin(
        new OpenApiPluginConfiguration()
            .withDocumentationPath("/openapi")
            .withDefinitionConfiguration((version, definition) -> definition
                .withOpenApiInfo((openApiInfo) -> {
                    openApiInfo.setTitle("Awesome App");
                    openApiInfo.setVersion("1.0.0");
                })
                .withServer((openApiServer) -> {
                    openApiServer.setUrl(("http://localhost:{port}{basePath}/" + version + "/"));
                    openApiServer.setDescription("Server description goes here");
                    openApiServer.addVariable("port", "8080", new String[] { "7070", "8080" }, "Port of the server");
                    openApiServer.addVariable("basePath", "", new String[] { "", "v1" }, "Base path of the server");
                })
                // Based on official example: https://swagger.io/docs/specification/authentication/oauth2/
                .withSecurity(new SecurityConfiguration()
                    .withSecurityScheme("BasicAuth", new BasicAuth())
                )
                .withDefinitionProcessor(content -> { // you can add whatever you want to this document using your favourite json api
                    content.set("test", new TextNode("Value"));
                    return content.toPrettyString();
                }))
            )
    ));

    SwaggerConfiguration swaggerConfiguration = new SwaggerConfiguration();
    swaggerConfiguration.setDocumentationPath(deprecatedDocsPath);
    config.plugins.register(new SwaggerPlugin(swaggerConfiguration));

    ReDocConfiguration reDocConfiguration = new ReDocConfiguration();
    reDocConfiguration.setDocumentationPath(deprecatedDocsPath);
    config.plugins.register(new ReDocPlugin(reDocConfiguration));

    // Get schemes annotated with @JsonScheme annotation
    for (JsonSchemaResource generatedJsonSchema : new JsonSchemaLoader().loadGeneratedSchemes()) {
        System.out.println(generatedJsonSchema.getName());
        System.out.println(generatedJsonSchema.getContentAsString());
    }
})
.start(8080);

Full example:

Clone this wiki locally