springfox-data-rest configuration not work - spring-boot

I follow the link to config.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>2.7.0</version>
</dependency>
#Configuration
#Import( {springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration.class})
public class WebMvcConfig extends WebMvcConfigurerAdapter{
......
}
#RepositoryRestResource(collectionResourceRel = "mails", path = "mails")
public interface TMessageMailDao extends PagingAndSortingRepository<TMessageMail, Long>{
}
But when I open http://localhost:8080/swagger-ui.html, there is nothing.
I know springfox-data-rest is still in incubation. Is that the reason it's not work? Or anything wrong?

You are missing #EnableSwagger2 annotation.
Make sure to create a Docket bean as shown in the example below.
#Configuration
#Import({SpringDataRestConfiguration.class})
#EnableSwagger2
public class WebMvcConfig extends WebMvcConfigurerAdapter {
...
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("example")
.select()
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo("Example API", "Example API"));
}
private ApiInfo apiInfo(String title, String description) {
return new ApiInfoBuilder()
.title(title)
.description(description)
.build();
}
}
Make sure to add the following dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
Once it's working, your swagger-ui.html will look something like this:
I want to scan two packages. How to include two base packages and not one?
Just Controllers
If you are just interested in including REST controllers and not any repository, you can specify any number of packages within apis method of Docket with the help of a custom method.
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("book")
.select()
.apis(exactPackages("com.basaki.controller", "com.basaki.model"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo("Example Springfox API",
"Example Springfox API"));
}
private static Predicate<RequestHandler> exactPackages(
final String... pkgs) {
return input -> {
String currentPkg =
input.declaringClass().getPackage().getName();
for (String pkg : pkgs) {
if (pkg.equals(currentPkg)) {
return true;
}
}
return false;
};
}
Controllers and Repositories
If you are interested in including REST controllers and repositories, you have to take advantage of paths method in Docket with the help of a custom method. The custom method takes path regexes.
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("book")
.select()
.paths(matchPathRegex("/books(/|$).*",
"/booxs(/|$).*", "/tokens(/|$).*",
"/ping(/|$).*"))
.build()
.apiInfo(apiInfo("Example Springfox API",
"Example Springfox API"));
}
private static Predicate<String> matchPathRegex(final String... pathRegexs) {
return new Predicate<String>() {
#Override
public boolean apply(String input) {
for (String pathRegex : pathRegexs) {
if (input.matches(pathRegex)) {
return true;
}
}
return false;
}
};
}

Thank you for Indra Basak 's help.
My configuration just have one problem.
#Configuration
#EnableSwagger2
#Import({SpringDataRestConfiguration.class})
This three annotations have to use together. I config #EnableSwagger2 in another configuration file.

Related

After deploy in jenkins, i can't find swagger

Actually, after i deployed my project on jenkins, i can't find swagger api docs.
what if our domain xxx.oooo.com, i've tried "xxx.oooo.com/swagger-ui/index.html", but can't still find. Also i tried ip4 address as well. but still doesn't work.
there is no problem about deploy, because there is no fail on jenkins.
i didnt work for front-end side, so i have no idea, but is it possible to be related with front-end about unable finding swagger api docs?..
i've also tried a lot of times through google, but still couldn't find answer yet. Plus, it works on local server really well!
here is my swaggerConfig.java file.
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
#Value("${swagger.info.title}")
private String title;
#Value("${swagger.info.desc}")
private String desc;
#Value("${swagger.info.version}")
private String version;
#Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.securityContexts(Arrays.asList(securityContext()))
.securitySchemes(Arrays.asList(apiKey()))
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.company.controller"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(desc)
.version(version)
.build();
}
public SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.build();
}
public List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accept all");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("Authorization", authorizationScopes));
}
public ApiKey apiKey() {
return new ApiKey("Authorization", "Authorization", "header");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
I am using
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
I also set up webConfig as well.
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*");
}
}

Unable to add application name to base URL after adding swagger3 in my Springboot project

When I was using springfox-swagger 2.9.0, I was using below code in my project.
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
Docket docket = null;
try{
if(!(profile.contains("local")|| (profile.contains("test"))
docket = new Docket(DocumentationType.SWAGGER_2)
.host(host)
.pathProvider(new RelativePathProvider(servletContext){
#Override
public String getApplicationBasePath(){
return "/api";
}
})
.select()
.apis(RequestHandlerSelectors.basePackage("org.app.controller"))
.paths(PathSelectors.any())
.build();
}
else{
docket = new Docket(DocumentationType.SWAGGER_2)
.host(host)
.select()
.apis(RequestHandlerSelectors.basePackage("org.app.controller"))
.paths(PathSelectors.any())
.build();
}
}
catch(Exception e){
logger.info("Unable to return docket",ex)
}
return docket;
}
}
After adding below swagger 3.0.0 dependency, my updated class is:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
#Configuration
public class SwaggerConfig {
#Bean
public Docket api() {
Docket docket = null;
try{
if(!(profile.contains("local")|| (profile.contains("test"))
docket = new Docket(DocumentationType.SWAGGER_2)
.host(host)
.pathProvider(new PathProvider(){
#Override
public String getOperationPath(String operationPath){
return operationPath.replace("/api","");
}
#Override
public String getResourceListingPath(String groupName, String apiDeclaration){
return null;
}
})
.select()
.apis(RequestHandlerSelectors.basePackage("org.app.controller"))
.paths(PathSelectors.any())
.build();
}
else{
docket = new Docket(DocumentationType.SWAGGER_2)
.host(host)
.select()
.apis(RequestHandlerSelectors.basePackage("org.app.controller"))
.paths(PathSelectors.any())
.build();
}
}
catch(Exception e){
logger.info("Unable to return docket",ex)
}
return docket;
}
}
After using this code , I am not able to append "/api" to my baseurl "localhost:8080" from updated swagger url.
http://localhost:8080/abc-api/swagger-ui/index.html#/
The base url should appear as "localhost:8080/api".
I tried creating separate bean for PathProvider implementation and then passed in argument but still same issue is there.
Could anyone please tell me what am I doing wrong here and how to create the baseurl as "/api" instead or "/" ?
This is not an answer to your problem but it might help you.
Since you are migrating anyway, consider using springdoc instead of Springfox. It is a newer library that is easier to use and way less error-prone than Springfox. We moved to it 2 years ago and we are very glad we did. There is very good documentation and tutorials online for it:
https://springdoc.org/
https://www.baeldung.com/spring-rest-openapi-documentation
It is also very active and you usually get your issues answered very fast on the github page.

Getting swagger-ui to display my codegen-generated API

I'm working on a springboot project. We're doing API first so we're generating code from an api.yaml. We're using openapi 3.0. The interfaces are being generated fine but when we browse to our swagger-ui URL, it says No operations defined in spec!
Here are the details:
#Configuration
#RequiredArgsConstructor
#EnableSwagger2
public class SwaggerConfig {
private final BuildProperties buildProperties;
#Bean
public Docket docketConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors
.basePackage("com.xyz.infrastructure.rest.spring.resource"))
.build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(buildProperties.getName())
.version(buildProperties.getVersion())
.build();
}
}
Our structure is:
com.xyz.infrastructure.rest.spring
|
|- config
|- SwaggerConfig
|- spec //autogenerated
|- dto //autogenerated
|- resource // implementations of interfaces found in spec
What are we missing?
We're using:
<dependency>
<groupId>io.swagger.codegen.v3</groupId>
<artifactId>swagger-codegen</artifactId>
<version>3.0.21</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Thank you!
We finally got it to work. Here's what did it for us:
Springfox version 3:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Using the io.swagger.codegen.v3 plugin.
This swagger config:
#Configuration
#EnableOpenApi
public class SwaggerConfig {
#Bean
public Docket docketConfig() {
return new Docket(DocumentationType.OAS_30)
.select()
.apis(RequestHandlerSelectors
.basePackage("com.xyz.infrastructure.rest.spring.resource"))
.build();
}
}
And make sure your classes in resource have the #RestController annotation.
I used like below:
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
//.apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("uz.xb.qr_project"))//*** base package
.paths(PathSelectors.any())
.build()
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Spring Boot REST API")
.description("\"Spring Boot REST API for Online Store\"")
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.contact(new Contact("John Thompson", "https://springframework.guru/about/", "john#springfrmework.guru"))
.build();
}
#Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")//**address of swagger ui
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
ApiController.java
#RestController
#RequestMapping
public class ApiController {
#Autowired
private ApiService apiService;
#GetMapping
public String swagger(){
return "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>REST API LIST</title>\n" +
" <meta http-equiv=\"refresh\" content=\"0; url=/qr_online/swagger-ui.html\" />\n" +
"</head>\n" +
"<body>\n" +
"REST API LIST\n" +
"</body>\n" +
"</html>";
}
//Or you can use like this inside controller
/*
#GetMapping
public void redirect(HttpServletResponse response) throws IOException {
response.sendRedirect("swagger-ui.html");
}
*/
}
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

swagger not detected when i remove #configuration

i try to integrate swagger into my spring boot project but i receive always an error :
"Error creating bean with name 'modelMapperImpl': Failed to introspect bean class [springfox.documentation.swagger2.mappers.ModelMapperImpl] " but when i remove #configuration from swaggerConfig swagger will not be detected ,here is my code :
WebConfig:
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE",
"PATCH");
}
}
SwaggerConfig
#EnableSwagger2
#Configuration
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
Try this approach.
#Configuration
#ConfigurationProperties(prefix = "mycompany.cors")
public class CorsSettings {
final private Logger log = LoggerFactory.getLogger(CorsSettings.class);
private List<String> origins = new ArrayList<>();
public CorsSettings() {
log.debug("construct CorsSettings");
}
public List<String> getOrigins() {
return this.origins;
}
#Bean
public WebMvcConfigurer corsConfigurer() {
if (origins != null) {
log.debug("corsOrgins=" + origins);
} else {
log.error("corsOrgins=null");
}
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins(origins.toArray(new String[origins.size()]));
}
};
}
}
Next in Config
#Configuration
public class SwaggerConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder().title("My Swagger API").description("This is a my swagger server")
.license("").licenseUrl("https://opensource.org/licenses/MIT").termsOfServiceUrl("").version("1.0.0")
.contact(new Contact("My name", "://www.mycompany.com", "myemail#mycompany.com"))
.build();
}
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.mycompany.path")).build()
.apiInfo(apiInfo());
}
}
Then in application.yml
mycompany:
cors:
origins:
- ${origin1:http://localhost:8080}
- ${origin2:http://localhost:8080}
- ${origin3:http://localhost:8080}
- ${origin4:http://localhost:8080}

Not able to get Swagger UI with spring boot

I am following the article at http://raibledesigns.com/rd/entry/documenting_your_spring_api_with.
Everything works fine but not able to integrate Swagger UI.
http://localhost:8080/docs/index.html
results in /error redirection.
I know this is an old question but maybe this will help someone with the similar problem in the future.
I followed similar tutorial to the one you mentioned and I made it work without a problem. I put my own document on how to setup a Swagger with UI in a Spring boot project couple of weeks ago. Maybe it will help you out since it is shorter and more up-to-date.
Add Maven dependencies
Stick these in your pom.xml:
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
<type>jar</type>
</dependency>
Add Swagger UI
Download the Swagger UI from github. Copy the dist folder into your webapp directory and rename dist to swagger (or any name you like).
Open the index.html file inside the copied directory and change the url in the first javascript function so it points to the /api-docs endpoint:
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "/project-name/api-docs";
}
Configure Swagger
Create a SwaggerConfig.java class and configure swagger there:
#Configuration
#EnableSwagger
#EnableAutoConfiguration
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
// Root level documentation
.apiInfo(new ApiInfo("Swagger-demo JSON API", "This service provides a JSON representation the service API", null, null, null, null))
.useDefaultResponseMessages(false)
// Map the specific URL patterns into Swagger
.includePatterns("/greeting.*");
}
}
Your swagger should be up and running now. Try accessing /project-name/swagger/index.html.
I'm answering this with swagger2 configuration inside a gradle based spring boot application. Following are the configuration required for Swagger2.
Add Gradle Configuartion
Add Gradle dependencies inside build.gradle file
dependencies {
compile("io.springfox:springfox-swagger2:2.0.2")
compile("io.springfox:springfox-swagger-ui:2.0.2")
}
Swagger2 Confugration Class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build().pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(
typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder().code(500).message("500 message")
.responseModel(new ModelRef("Error")).build()))
.securitySchemes(newArrayList(apiKey())).securityContexts(newArrayList(securityContext()))
.apiInfo(apiInfo());
}
#Autowired
private TypeResolver typeResolver;
private ApiKey apiKey() {
return new ApiKey("mykey", "api_key", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*")).build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("mykey", authorizationScopes));
}
#Bean
SecurityConfiguration security() {
return new SecurityConfiguration("123456", "test-app-realm", "clientapp", "apiKey");
}
#Bean
UiConfiguration uiConfig() {
return new UiConfiguration("validatorUrl");
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("DSM API", "API for DSM", "1.0.0", "termsOfServiceUrl",
"nijo#ndimensionz.com", null, null);
return apiInfo;
}
}
Add Swagger UI
Download the Swagger UI from github. Copy the dist folder into your src/main/resources/static directory and rename dist to swagger
HomeController.class
#Api(basePath = "/", value = "/", description = "Home Controller")
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "redirect:swagger-ui.html";
}
}
MyApplication.class
#SpringBootApplication
#ComponentScan(basePackageClasses = SwaggerConfig.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Configure your spring boot application with dependencies and run to see the API.
the url will be http://localhost:8080/v2/swagger-ui.html
you can also customize this as above answer.
I too face same problem. I was able to see json but not swagger ui after adding dest folder aslo. In initialize class which extends SpringBootServletInitializer I added below method then it was working perfect
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleWebStaticApplication.class);
}
please refer link
Here is my working configuration incase it helps anyone else
#Configuration
#EnableSwagger2
#Profile({"!production"})
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {
#Autowired
private ServletContext servletContext;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost")
.directModelSubstitute(LocalDate.class, Date.class)
.pathProvider(new RelativePathProvider(servletContext) {
#Override
public String getApplicationBasePath() {
return "/docs";
}
})
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Since I am also using Spring security, I also had to add the following to my whitelist:
private String[] swaggerWhiteList = {"/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/swagger.json", "/webjars/**"};
Then I could access it using the following url:
http://localhost:8080/docs/swagger-ui.html

Resources