Springfox: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(42 intermediate revisions by the same user not shown)
Line 7: Line 7:
=Internal=
=Internal=


* [[Swagger]]
* [[Generating Swagger/OpenAPI Specification from Spring Code]]
* [[Generating Swagger/OpenAPI Specification from Spring Code]]


=Overview=
=Overview=


Springfox is a suite of Java libraries for automating the generation of machine and human readable specification for JSON APIs written with [[Spring Framework]].
Springfox is a suite of Java libraries for automating the generation of machine and human readable specification for JSON APIs written with [[Spring Framework]]. Springfox works by examining an application, once, at runtime to infer API semantics based on Spring configurations, class structure and various compile time java annotations.
 
=Dependencies=
 
<syntaxhighlight lang='groovy'>
repositories {
 
  jcenter()
}
 
dependencies {
 
    implementation "io.springfox:springfox-swagger2:2.9.2"
}
</syntaxhighlight>
 
=Essential Classes=
 
====Docket====
 
springfox.documentation.spring.web.plugins.Docket: the primary API configuration mechanism.
 
====ApiSelectorBuilder====
 
ApiSelectorBuilder provides fine grained control over the endpoints exposed via swagger.
 
=Annotations=
 
* [[@EnableSwagger2]]
 
=Security Schemas=
 
The following security schemas are available to protect the API:
* ApiKey
* BasicAuth
* OAuth
 
=Models=
 
==Non-reachable Model==
 
A model that should be described in the generated specification but is not explicitly used in any operation.
 
=Generating Swagger/OpenAPI Specification from Spring Code with Springfox=
 
==External==
 
* https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/
* http://springfox.github.io/springfox/docs/current/
* https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
 
==Playground Example==
 
{{External|https://github.com/ovidiuf/playground/tree/master/spring/spring-boot/rest-to-swagger-with-springfox|Playground rest-to-swagger-with-springfox]}}
 
==General Considerations==
 
This section shows how to dynamically generate a Swagger 2.0 specification of the implemented API at runtime, as JSON. The second part of the section shows how to enable UI support for browsing the API specification.
 
==Generating the Swagger Specification==
 
At this point, only the [[#Dependencies|"io.springfox:springfox-swagger2" dependency]] is needed. This dependency contains all the functionality Springfox needs to generate the specification of the API, in JSON format, at runtime.
 
There are two essential code changes:
 
1. Annotate the Spring Boot application class, or a Configuration with [[@EnableSwagger2]]. It is preferable to provide a separated Configuration class, dedicated to Swagger.
 
2. Expose a configured [[#Docket|Docket]] instance as a bean:
 
<syntaxhighlight lang='java'>
@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
 
  // ...
 
  @Bean
  public Docket swaggerSpecification() {
 
    Docket docket = new Docket(DocumentationType.SWAGGER_2);
 
    // ApiSelectorBuilder gives fine grained control over the endpoints exposed via swagger
    ApiSelectorBuilder apiSelectorBuilder = docket.select();
    apiSelectorBuilder.
      apis(RequestHandlerSelectors.any()).
      paths(PathSelectors.any()).
      build();
 
  // adds a servlet path mapping, when the servlet has a path mapping. This prefixes paths with the provided path mapping
  docket.
    pathMapping("/").
    tags(new Tag("A Service", "All APIs relating to A"));
 
  return docket;
}
</syntaxhighlight>
 
If these two elements are present, the Spring application will generate its JSON-formatted. Swagger2 specification while invoked as: http://localhost:8080/v2/api-docs
 
For a complete example see [https://github.com/ovidiuf/playground/blob/690078af4aa73e437ad4dcc714104314e0fa0adb/spring/spring-boot/rest-to-swagger-with-springfox/src/main/java/playground/spring/boot/rest/rest2swagger/SwaggerConfiguration.java#L45-L103 SwaggerConfiguration.java].
 
==UI Support==
 
===UI Support Dependency===
 
<syntaxhighlight lang='groovy'>
dependencies {
 
    implementation 'io.springfox:springfox-swagger-ui:2.9.2'
}
</syntaxhighlight>
 
===Code Changes===
 
Spring Boot should auto-configure Springfox UI support, but for some reason it didn't last time I tried. The following resource handlers were added explicitly in the code, as part of a class that extends WebMvcConfigurerAdapter, and is annotated with @EnableWebMvc:
 
<syntaxhighlight lang='java'>
@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
 
  // ...
 
  @Override
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {
 
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");
 
    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}
</syntaxhighlight>
 
===UI Access===
 
The UI is accessible at http://localhost:8080/swagger-ui.html
 
==Generating the Swagger Specification as Artifact of Gradle-driven Build Process==
 
A possible way - probably not the best - is to execute the application as an integration test, send an "/v2/api-docs" request into it and capture the output. This is an example of how to do it: {{External|[https://github.com/ovidiuf/playground/blob/master/spring/spring-boot/rest-to-swagger-with-springfox/src/test/java/playground/spring/boot/rest/rest2swagger/SwaggerSpecificationGenerator.java Playground rest-to-swagger-with-springfox SwaggerSpecificationGenerator.java]}}
 
===External===
 
* https://github.com/luchob/swagger-example

Latest revision as of 00:01, 15 February 2019

External

Internal

Overview

Springfox is a suite of Java libraries for automating the generation of machine and human readable specification for JSON APIs written with Spring Framework. Springfox works by examining an application, once, at runtime to infer API semantics based on Spring configurations, class structure and various compile time java annotations.

Dependencies

repositories {

   jcenter()
}

dependencies {

    implementation "io.springfox:springfox-swagger2:2.9.2"
}

Essential Classes

Docket

springfox.documentation.spring.web.plugins.Docket: the primary API configuration mechanism.

ApiSelectorBuilder

ApiSelectorBuilder provides fine grained control over the endpoints exposed via swagger.

Annotations

Security Schemas

The following security schemas are available to protect the API:

  • ApiKey
  • BasicAuth
  • OAuth

Models

Non-reachable Model

A model that should be described in the generated specification but is not explicitly used in any operation.

Generating Swagger/OpenAPI Specification from Spring Code with Springfox

External

Playground Example

https://github.com/ovidiuf/playground/tree/master/spring/spring-boot/rest-to-swagger-with-springfox

General Considerations

This section shows how to dynamically generate a Swagger 2.0 specification of the implemented API at runtime, as JSON. The second part of the section shows how to enable UI support for browsing the API specification.

Generating the Swagger Specification

At this point, only the "io.springfox:springfox-swagger2" dependency is needed. This dependency contains all the functionality Springfox needs to generate the specification of the API, in JSON format, at runtime.

There are two essential code changes:

1. Annotate the Spring Boot application class, or a Configuration with @EnableSwagger2. It is preferable to provide a separated Configuration class, dedicated to Swagger.

2. Expose a configured Docket instance as a bean:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {

  // ...

  @Bean
  public Docket swaggerSpecification() {

    Docket docket = new Docket(DocumentationType.SWAGGER_2);

    // ApiSelectorBuilder gives fine grained control over the endpoints exposed via swagger
    ApiSelectorBuilder apiSelectorBuilder = docket.select();
    apiSelectorBuilder.
      apis(RequestHandlerSelectors.any()).
      paths(PathSelectors.any()).
      build();

  // adds a servlet path mapping, when the servlet has a path mapping. This prefixes paths with the provided path mapping
  docket.
    pathMapping("/").
    tags(new Tag("A Service", "All APIs relating to A"));

  return docket;
}

If these two elements are present, the Spring application will generate its JSON-formatted. Swagger2 specification while invoked as: http://localhost:8080/v2/api-docs

For a complete example see SwaggerConfiguration.java.

UI Support

UI Support Dependency

dependencies {

    implementation 'io.springfox:springfox-swagger-ui:2.9.2'
}

Code Changes

Spring Boot should auto-configure Springfox UI support, but for some reason it didn't last time I tried. The following resource handlers were added explicitly in the code, as part of a class that extends WebMvcConfigurerAdapter, and is annotated with @EnableWebMvc:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
  
  // ...

  @Override
  protected void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

UI Access

The UI is accessible at http://localhost:8080/swagger-ui.html

Generating the Swagger Specification as Artifact of Gradle-driven Build Process

A possible way - probably not the best - is to execute the application as an integration test, send an "/v2/api-docs" request into it and capture the output. This is an example of how to do it:

Playground rest-to-swagger-with-springfox SwaggerSpecificationGenerator.java

External