swagger with spring webflux cannot find Publisher«ResponseEntity«object»» - spring

I am trying to use swagger with spring webflux, but for some reason it gives an error message
Could not resolve reference because of: Could not resolve pointer:
/definitions/Publisher«ResponseEntity«object»» does not exist in
document
here it is the sawagger config
#Configuration
#EnableSwagger2WebFlux
public class SwaggerConfig {
private final SwaggerDocketBuilder builder;
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Reactive Documentation")
.description("Reactive API Documentation")
.version("1.0.0")
.build();
}
#Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
.enable(true)
.select()
.paths(PathSelectors.any())
.build();
}
}

Found the answer
I have added .genericModelSubstitutes(Mono.class, Flux.class, Publisher.class);
the new docket()
#Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(this.apiInfo())
.enable(true)
.select()
.paths(PathSelectors.any())
.build()
.genericModelSubstitutes(Mono.class, Flux.class, Publisher.class);
}

Related

Swagger Ui hangs for api endpoint in spring boot

My client api endpoint is not loading in swagger UI as shown in the image what I need to do? It always show loading icon when I click on any client controller api like get,post
Please post answer Thank You
see picture
SwaggerConfig.groovy
#Configuration
#EnableSwagger2
class SwaggerConfig {
#Bean
Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any()
.paths(PathSelectors.any())
.build().apiInfo(metaData())
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Swagger Example")
.description("\"Swagger configuration for application \"")
.version("1.1.0")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.build()
}
}
ClientController.groovy
#RestController
#RequestMapping('/client')
class ClientController {
#Autowired
ClientService clientService
#GetMapping('/')
ResponseEntity<List<Client>> getAllClients() {
List<Client> clients = clientService.getAllClients()
return new ResponseEntity<>(clients, HttpStatus.OK)
}
#GetMapping('/{clientId}')
ResponseEntity<Client> getClientById(#PathVariable("clientId") Integer clientId) {
return new ResponseEntity<>(clientService.getClientById(clientId), HttpStatus.OK)
}
#PostMapping('/create')
ResponseEntity<Client> createClient(#RequestBody Client client) {
return new ResponseEntity<>(clientService.addClient(client), HttpStatus.CREATED)
}
#PutMapping('/update/{clientId}')
ResponseEntity<Client> updateClient(#PathVariable("clientId") Integer clientId, #RequestBody Client client) {
clientService.updateClient(client, clientId)
return new ResponseEntity<>(clientService.getClientById(clientId), HttpStatus.OK)
}
#DeleteMapping('/delete/{clientId}')
ResponseEntity<Client> deleteClient(#PathVariable("clientId") Integer clientId) {
clientService.deleteClientById(clientId)
return new ResponseEntity<>(HttpStatus.NO_CONTENT)
}
}

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.

How to pattern match of a API while exposing to Swagger2 in Spring Boot?

Below is the controller for which I need to write swagger2 API documents:
#RestController
#RequestMapping("/abc/def/pqr")
public class Controller {
#GetMapping(path = "", consumes = "application/json", produces = "application/json")
#ResponseBody
public <T> PagedResources<SomeResource> get(Pageable pageable,
Assembler assembler) {
Page<Something> somethings = service.get(pageable);
return pagedAssembler.toResource(somethings, assembler);
}
}
Below is the code for through which I am trying to write swagger to API documentations:
#Bean
public Docket swaggerConfiguration() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(PathSelectors.ant("/abc/def/pqr/"))
.build()
}
But even after writing it, this API is not exposing to swagger2. Wherever, I can understand the problem I thing that there is some problem in PathSelectors.ant("/abc/def/pqr/") . So, please someone can help me then it's better for me.
Thanks in advance...
Try this
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select() .apis(RequestHandlerSelectors.basePackage("your.base.package"))
.paths(regex("/product.*"))
.build();
}
}

Example of Swagger Configuration with Security in Spring Boot

Someone has an example of swagger security with spring boot?
My docket config it is like this:
#Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.paths(PathSelectors.any())
.build()
.apiInfo(metaData());
}
to configure swagger with security you should set the securityContexts like this :
private final TypeResolver typeResolver;
// constructor
public SwaggerConfig(TypeResolver typeResolver) {
this.typeResolver = typeResolver;
}
#Bean
public Docket apiBatch() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("path.to.package"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Lists.newArrayList(apiKey()))
.securityContexts(Collections.singletonList(securityContext()))
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
/**
* add as header the Authorization header
*
* #return
*/
private ApiKey apiKey() {
return new ApiKey("apiKey", "Authorization", "header");
}
/**
* demand the authorization for access on /api/v1/**
*
* #return
*/
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/api/v1.*")).build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope(
"global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Collections.singletonList(new SecurityReference("apiKey",
authorizationScopes));
}
private AlternateTypeRule getAlternateTypeRule(Type sourceType, Type sourceGenericType,
Type targetType, Type targetGenericType) {
return AlternateTypeRules.newRule(typeResolver.resolve(sourceType, sourceGenericType),
typeResolver.resolve(targetType, targetGenericType));
}
Edit
I've added the TypeResolver property of fasterxml classmate library ( compile group: 'com.fasterxml', name: 'classmate', version: '1.3.1' )
Note that SwaggerConfig is the config class name

springboot Multiple Dockets with the same group name are not supported

I have the follwoing spring boot configuration for swagger, when service starts up i get the following error, im not sure exactly why this would be the case. I have followed a tutorial and it works for them.
java.lang.IllegalStateException: Multiple Dockets with the same group name are not supported. The following duplicate groups were discovered. default
#Configuration
#EnableSwagger2
#Import(BeanValidatorPluginsConfiguration.class)
public class SpringFoxConfig {
#Bean
public Docket apiDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("test.rest"))
.paths(PathSelectors.ant("/test/**"))
.build()
.apiInfo(apiInfo());
}
// Describe the apis
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("test")
.description("Test")
.version("1.0.0")
.license("vvv")
.build();
}
}
i also have another config
#OurApp
#EnableSwagger2
public class CoreApp extends OurApp {
}
Here you are trying to do multiple Dockets with the same group name, which is not acceptable. Please review the link provided.
groupName(java.lang.String groupName) If more than one instance of
Docket exists, each one must have a unique groupName as supplied by
this method. Documentation
public class Docket implements DocumentationPlugin {
public static final String DEFAULT_GROUP_NAME = "default";
}
You can see above DocumentPlugin has groupname as "default".
public Docket(DocumentationType documentationType) {
this.apiInfo = ApiInfo.DEFAULT;
this.groupName = "default";
And above has "default" as group name.
So, you need to have two different group names for both the Dockets.
All you need to do is change your code as below: overwrite the existing default groupname.
#Configuration
#EnableSwagger2
#Import(BeanValidatorPluginsConfiguration.class)
public class SpringFoxConfig {
#Bean
public Docket apiDocket() {
String groupName = "Swagger";
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("test.rest"))
.paths(PathSelectors.ant("/test/**"))
.build()
.groupName(groupName)
.apiInfo(apiInfo());
}
// Describe the apis
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("test")
.description("Test")
.version("1.0.0")
.license("vvv")
.build();
}
}
Seems like you have given the same group name which is not accepted, please check and set the group name properly.

Resources