Code Monkey home page Code Monkey logo

springdoc.github.io's Introduction

Octocat Build Status Quality Gate Known Vulnerabilities Stack Exchange questions

IMPORTANT: springdoc-openapi v1.8.0 is the latest Open Source release supporting Spring Boot 2.x and 1.x.

An extended support for springdoc-openapi v1 project is now available for organizations that need support beyond 2023.

For more details, feel free to reach out: [email protected]

springdoc-openapi is on Open Collective. If you ❤️ this project consider becoming a sponsor.

This project is sponsored by

  

Table of Contents

Introduction

The springdoc-openapi Java library helps automating the generation of API documentation using Spring Boot projects. springdoc-openapi works by examining an application at runtime to infer API semantics based on Spring configurations, class structure and various annotations.

The library automatically generates documentation in JSON/YAML and HTML formatted pages. The generated documentation can be complemented using swagger-api annotations.

This library supports:

  • OpenAPI 3
  • Spring-boot v3 (Java 17 & Jakarta EE 9)
  • JSR-303, specifically for @NotNull, @Min, @Max, and @Size.
  • Swagger-ui
  • OAuth 2
  • GraalVM native images

The following video introduces the Library:

For spring-boot v3 support, make sure you use springdoc-openapi v2

This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal)

Getting Started

Library for springdoc-openapi integration with spring-boot and swagger-ui

  • Automatically deploys swagger-ui to a Spring Boot 3.x application
  • Documentation will be available in HTML format, using the official swagger-ui jars.
  • The Swagger UI page should then be available at http://server: port/context-path/swagger-ui.html and the OpenAPI description will be available at the following url for json format: http://server:port/context-path/v3/api-docs
    • server: The server name or IP
    • port: The server port
    • context-path: The context path of the application
  • Documentation can be available in yaml format as well, on the following path: /v3/api-docs.yaml
  • Add the springdoc-openapi-ui library to the list of your project dependencies (No additional configuration is needed):
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file:
# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

Spring-boot with OpenAPI Demo applications.

Branching

Integration of the library in a Spring Boot 3.x project without the swagger-ui:

  • Documentation will be available at the following url for json format: http://server: port/context-path/v3/api-docs
    • server: The server name or IP
    • port: The server port
    • context-path: The context path of the application
  • Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
  • Add the library to the list of your project dependencies. (No additional configuration is needed)
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the OpenAPI documentation in Json format, add a custom springdoc property, in your spring-boot configuration file:
# /api-docs endpoint custom path
springdoc.api-docs.path=/api-docs
  • This step is optional: If you want to disable springdoc-openapi endpoints, add a custom springdoc property, in your spring-boot configuration file:
# disable api-docs
springdoc.api-docs.enabled=false

Error Handling for REST using @ControllerAdvice

To generate documentation automatically, make sure all the methods declare the HTTP Code responses using the annotation: @ResponseStatus.

Adding API Information and Security documentation

The library uses spring-boot application auto-configured packages to scan for the following annotations in spring beans: OpenAPIDefinition and Info. These annotations declare, API Information: Title, version, licence, security, servers, tags, security and externalDocs. For better performance of documentation generation, declare @OpenAPIDefinition and @SecurityScheme annotations within a Spring managed bean.

spring-webflux support with Annotated Controllers

  • Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
  • Add the library to the list of your project dependencies (No additional configuration is needed)
   <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
      <version>last-release-version</version>
   </dependency>
  • This step is optional: For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file:
# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

The springdoc-openapi libraries are hosted on maven central repository. The artifacts can be viewed accessed at the following locations:

Releases:

Snapshots:

Acknowledgements

Contributors

springdoc-openapi is relevant and updated regularly due to the valuable contributions from its contributors.

Thanks you all for your support!

Additional Support

  • Spring Team - Thanks for their support by sharing all relevant resources around Spring projects.
  • JetBrains - Thanks a lot for supporting springdoc-openapi project.

JenBrains logo

springdoc.github.io's People

Contributors

aoudiamoncef avatar ashutoshgngwr avatar aubreyyan avatar bnasslahsen avatar buzzerrookie avatar chrisnellis avatar dancer1325 avatar decat-simona avatar dgruntz avatar fxprunayre avatar kennysoft avatar key-del-jeeinho avatar kgeis avatar mc1arke avatar natrem avatar pirocraft avatar seregamorph avatar shaburov avatar uc4w6c avatar valery1707 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

springdoc.github.io's Issues

Misleading docs - web UI url's

Describe the bug

The docs here explicitly direct user to expect the web UI under the endpoints http://server:port/context-path/swagger-ui.html and http://server:port/context-path/v3/api-docs and as such to configure Spring security against those url's.

In reality, though, the following security config works:

				.and().authorizeRequests().antMatchers("/api-docs/**").permitAll()
				.and().authorizeRequests().antMatchers("/swagger-ui.html").permitAll()
				.and().authorizeRequests().antMatchers("/swagger-ui/**").permitAll()

Note the lack of 'v3' before api-docs.

Additionally, swagger-ui.html is redundant as it's simply redirecting to swagger-ui/index.html. It will not work unless user allows the swagger-ui/** path and swagger-ui/index.html will work already with just that path without the separate rule for swagger-ui.html.

I expect that most real-life spring projects use spring security so omitting this config step is adding headache for every new user.

sprindoc show actuator setting in app yaml does not refer to management port value

show-actuator: true
The above setting for sprindoc in app yaml does not refer to management port value that is set to -Dmanagement.server.port=
show actuator always look in the same port where app is running.

If actuator is using differ mgmt server port then it fails. We have to remove this show actuator setting to make it work.

@ParameterObject: there are no parameters if there are no get methods in the model.

Version: org.springdoc:springdoc-openapi-ui:1.6.6

There are no parameters in swagger

  • If ParameterObject without get methods
    image
  • If ParameterObject has a fluent chain get methods (without get prefix)
    image

The only working option. If there is a getter and only prefixed with 'get'.

image

The problem lies in the fact that the DelegatingMethodParameter.customize() method calls inside MethodParameterPojoExtractor.extractFrom(paramClass) which operates on methods, but in fact it would be worth working directly with annotated fields.

Secondly, POJO, unlike JavaBean, does not require getters and setters. I can work with POJO fields directly if they are declared as public/package-privat/protected.

But the main problem is that this behavior is not documented ANYWHERE. Wasted a lot of time on trivia.
Add at least information about this nuance to https://springdoc.org/faq.html

image

Customizing swagger static resources

See issue.

OpenAPI Configuration

@Configuration
public class OpenApiConfig {
  @Bean
  public SwaggerIndexTransformer swaggerIndexTransformer(SwaggerUiConfigProperties sUiConfig,
                                                         SwaggerUiOAuthProperties sUiOAuthProperties,
                                                         SwaggerUiConfigParameters sUiConfigParameters,
                                                         SwaggerWelcomeCommon sWelcomeCommon) {
      return new SwaggerCodeBlockTransformer(sUiConfig, sUiOAuthProperties, sUiConfigParameters, sWelcomeCommon);
  }
}

Transformer

public class SwaggerCodeBlockTransformer extends SwaggerIndexPageTransformer {

    private static final String OLD = ".renderedMarkdown code{" +
                                      "background:rgba(0,0,0,.05);" +
                                      "border-radius:4px;" +
                                      "color:#9012fe;" +
                                      "font-family:monospace;" +
                                      "font-size:14px;font-weight:600;" +
                                      "padding:5px 7px}";
    private static final String NEW = ".renderedMarkdown code{" +
                                      "color:#9012fe;" +
                                      "font-family:monospace;" +
                                      "font-size:14px;font-weight:600}";

    public SwaggerCodeBlockTransformer(SwaggerUiConfigProperties swaggerUiConfig,
                                       SwaggerUiOAuthProperties swaggerUiOAuthProperties,
                                       SwaggerUiConfigParameters swaggerUiConfigParameters,
                                       SwaggerWelcomeCommon swaggerWelcomeCommon) {
        super(swaggerUiConfig, swaggerUiOAuthProperties, swaggerUiConfigParameters, swaggerWelcomeCommon);
    }

    @Override
    public Resource transform(HttpServletRequest request,
                              Resource resource,
                              ResourceTransformerChain transformerChain) throws IOException {
        if (resource.toString().contains("swagger-ui.css")) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
                final String css = reader.lines().collect(Collectors.joining());
                final byte[] transformedContent = css.replace(OLD, NEW).getBytes();
                return  new TransformedResource(resource, transformedContent);
            }
        }
        return super.transform(request, resource, transformerChain);
    }

}

"Deep Linking documentation" - broken link

https://springdoc.org/#swagger-ui-properties

springdoc.swagger-ui.deepLinking | false | Boolean. If set to true, enables deep linking for tags and operations. See the [Deep Linking documentation](/docs/usage/deep-linking.md) for more information

The link is literally rendered as [Deep Linking documentation](/docs/usage/deep-linking.md).
And I can see no such document in repo.

The corresponding link is actually also broken at https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ . Leads to 404.

Invalid path for api-docs.yaml in full documentation

Hello, I noticed a small inconsistency in the documentation.

The full documentation found at https://springdoc.org/ mentions /v3/api-docs.yml in several places for accessing the API documentation in yaml format. However, the actual path should be /v3/api-docs.yaml as stated in the README. Trying to access /v3/api-docs.yml returns the Whitelabel Error page, while /v3/api-docs.yaml actually downloads the expected API documentation in yaml format.

A bit more Gradle plugin docs, please?

It is not very clear what kind of dependencies need to be:

  • Implementation?
  • developerOnly?
  • runtimeOnly?

I am currently going with this:

dependencies {
   ...
    //SpringDoc OpenAPI
    def springDocVersion = '1.6.11'
    implementation "org.springdoc:springdoc-openapi-ui:${springDocVersion}"
    implementation "org.springdoc:springdoc-openapi-webmvc-core:${springDocVersion}"
    implementation "org.springdoc:springdoc-openapi-webflux-ui:${springDocVersion}"
    implementation "org.springdoc:springdoc-openapi-hateoas:${springDocVersion}"
    implementation "org.springdoc:springdoc-openapi-data-rest:${springDocVersion}"
}

but would prefer not include in the final jar things that are not needed at runtime.

Remove code duplication with AsciiDoc's Include Directive

As can be seen here, the documentation is duplicated across src/docs/asciidoc and src/docs/asciidoc/v1, which is not only a burden to maintain, but also runs a high risk of them going out of sync, as shown here.

The solution is to create folder src/docs/asciidoc/common and use AsciiDoc's include directive:

An include directive imports content from a separate file or URL into the content of the current document. When the current document is processed, the include directive syntax is replaced by the contents of the include file. Think of the include directive like a file expander. [Source]

/docs
├── common
├── v1
└── v2

For SpringDoc OpenAPI 1.6, Swagger UI unable to render definition

Describe the bug

Swagger UI page complains about rendering the definition, shows error on page saying:
http://localhost:8080/swagger-ui/index.html

Unable to render this definition
The provided definition does not specify a valid version field.

Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).

when running the Spring Boot Maven plugin:

$ mvn clean spring-boot:run

To Reproduce

Steps to reproduce the behavior:

  • What version of spring-boot you are using?

Using Spring Boot 2.6:

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.14</version>
    <!-- # lookup parent from repository -->
    <relativePath />
  </parent>
  • What modules and versions of springdoc-openapi are you using?

Using SpringDoc 1.6:

    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.6.15</version>
    </dependency>
    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-security</artifactId>
      <version>1.6.15</version>
    </dependency>
  • How are you running the application?

Run using the Spring Boot Maven plugin:

$ mvn clean spring-boot:run

Expected behavior

Swagger UI does not throw error

Additional context

Config:

springdoc:
  writer-with-default-pretty-printer: true
  api-docs:
    enabled: true
    version: "openapi_3_0"
  swagger-ui:
    enabled: true
    operations-sorter: "method"
    tags-sorter: "alpha"
    display-request-duration: true

Using custom HTTP message converters:

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    messageConverters.add(new StringHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter(JsonUtils.createObjectMapper()));
  }

Unable to see JSON spec at:
http://localhost:8080/v3/api-docs
only shows some kind of Base64 output (not JSON)

FAQ links to wrong file for OpenApiCustomiser example

Is your feature request related to a problem? Please describe.

  • A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

I'm always frustrated when I click on a link from documentation and it's an empty test file.

  • What is the actual result using OpenAPI Description (yml or json)?

image

Describe the solution you'd like

  • A clear and concise description of what you want to happen.
  • What is the expected result using OpenAPI Description (yml or json)?

Update link to https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-webflux-core/src/test/java/test/org/springdoc/api/app39/SpringDocTestApp.java

Describe alternatives you've considered

  • A clear and concise description of any alternative solutions or features you've considered.

None

Additional context

  • Add any other context or screenshots about the feature request here.

None

Fix documentation for programmatic RouterFunctions

Edit:
This is just a documentation fix. On the main springdoc page for the programmatic openapi feature, you should point out that the route() method in your example is not the normal route() method from functional spring webflux routing. Looking more closely at the example code and javadocs, I see you have a SpringdocRouteBuilder.route() that is completely different than the normal spring RouterFunctions.route() method that people are used to calling.

The fact these are different methods isn't mentioned in your documentation, and since you do a static import in the example code, it was really easy to miss.

Original:

Describe the bug
You can't create a RouterFunction with programmatic openapi details

@Bean RouterFunction<ServerResponse> myroute() {
  return route().GET("/foo", HANDLER_FUNCTION, ops -> ops.operationId("hello")).build()
}

like the documentation says here.

To Reproduce
Steps to reproduce the behavior:

  • SpringBoot 2.7.4
  • Spring WebFlux 5.3.23
  • SpringDoc 1.6.11
  • Using springdoc-openapi-common, springdoc-openapi-webflux-core, springdoc-openapi-webflux-ui
  • Expecting the application to compile and generate openapi document
  • It doesn't compile because there is no method signature in RouterFunction.Builder for GET() that takes that combination of parameters.

Expected behavior

  • This spring commit shows the expected behavior that should compile
  • The expected result is to compile and generate any openapi output at all

Additional context

Travis CI build is broken

$ script/bootstrap
/home/travis/.travis/functions: line 109: script/bootstrap: Permission denied
The command "script/bootstrap" failed and exited with 126 during .

.travis.yml is missing the bash command before the scripts it's trying to invoke.

Removing webjars-locator-core broke using a provided spec.

Describe the bug

It appears that attempting to use a provided spec as documented here is broken since webjars-locator-core was removed in springdoc/springdoc-openapi#2173

setting springdoc.api-docs.enabled=false disables autoconfiguration which results in the new SpringDocsUIConfiguration not being configured - which causes a 404 when attempting to resolve the webjar.

I believe the instructions likely need updated to include defining a bean like:

@Bean
SpringDocsUIConfiguration springDocsUiConfiguration(Optional<SwaggerUiConfigProperties> optionalSwaggerUiConfigProperties){
    return new SpringDocsUIConfiguration(optionalSwaggerUiConfigProperties);
}

To Reproduce

  • Boot 2.7.12
  • spring-doc 1.7.0
  • Follow configuration steps here

Expected behavior

swagger-ui loads

favicon same a Spring project.

I have noticed that your favicon is the same as Spring project. I would suggest you use the nice icon you are using on the documentation page.

Non-existing class in documentation

Hello,
as metioned in issue: springdoc/springdoc-openapi#2321
I am supposed to register this Bean:

@Bean
    fun springDocsUiConfiguration(optionalSwaggerUiConfigProperties: Optional<SwaggerUiConfigProperties?>?): SpringDocsUIConfiguration? {
        return SpringDocsUIConfiguration(optionalSwaggerUiConfigProperties)
    }

But this class doesn't exist.

swagger-ui is not showing "select a definition" instead shows Explore option with text box

Issue
I have spring mvc project without spring boot that integrated springdoc-openapi as mentioned in the document. Everything works fine. but one issue seen in UI where I could not see "select a definition" with list of groups instead it was showing Text box with Explore option.

springdoc-openapi-ui - 1.6.4
spring-boot & spring-boot-autoconfigure - 2.6.2

Screen shot taken from non spring boot app
image

If i specify api-docs path manually, it works fine. I tried with simple spring boot project where I could see the select a definition option. Is something am i missing in non spring boot integration.

Screen shot taken from spring boot app

image

Clarify compatibility matrix

As I read it was ambigious to me what you mean with the versions you mention. Are the mentioned Spring Boot versions the minimal required version or did you only test the mentioned springdoc version against the mentioned spring Boot version.
For example, is Spring 2.6.x the minimal requirement for springdoc 1.6.x? ...or is it possible to use it with 2.5.x as well (but you didn't test it)?

document which regex dialect use use/support with sprindoc-openapi

I put a lot of energy in evolving a regex but when I put it into the @pattern annotation I got the message: Conditionals are not supported in this regex dialect.
It would be helpful to document the used regex dialect that developers can code against.
Which dialect is the proper one to use with sprimgdoc-openapi?

Wrong springboot version for reverse proxy faq

In the docs/faq.html file, line 582, you mentione "Spring Boot 3.2".
I think this is an error because server.forward-headers-strategy configuration is available since Spring Boot 2.0.

I don't know how I can create pull request but you should fix that.

Sincerely

Choose a new favicon for the docs page

The existing favicon does not have quadratic dimensions and it's not really usable to recognize it in a browser. Would be great if you could create a modern one just with the logo and maybe a transparent background.

screenshot-20240305-183058

Kotlin module for v2?

In v2.0.0 there seems to be no Kotlin module, yet the doc mentions otherwise. Latest on Maven Central is 1.6.13.

Documentation issue: "OpenAPICustomiser"

In the full documentation section 11.27. How can I customise the OpenAPI object?, there's a code example that does not compile.

@Bean
public OpenAPICustomiser consumerTypeHeaderOpenAPICustomiser() {
return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
    .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myConsumerTypeHeader")));
}

The issue is that there is no class named OpenAPICustomiser. Instead, it is called OpenApiCustomiser.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.