Git Product home page Git Product logo

springfox-demos's Introduction

Springfox

Join the chat at https://gitter.im/springfox/springfox FOSSA Status Download Project Stats

Build Status Coverage Code Analysis
Circle CI codecov Quality Gate Status
Sonar Cloud
Security Rating
Vulnerabilities
Maintainability Rating
Reliability Rating
Technical Debt
Coverage

About

For more information on this project visit the Springfox Website or http://springfox.github.io/springfox/

Useful links

Getting Started

For new projects

For Maven

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

For Gradle

  implementation "io.springfox:springfox-boot-starter:<version>"

Migrating from earlier snapshot

Spring Boot Applications

NOTE: Would love feedback to make this better

  1. Remove explicit dependencies on springfox-swagger2
  2. Remove any @EnableSwagger2... annotations
  3. Add the springfox-boot-starter dependency
  4. Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces.

Migrating from existing 2.x version

Spring Boot Applications

NOTE: Would love feedback to make this better

  1. Remove explicit dependencies on springfox-swagger2
  2. Remove the @EnableSwagger2 annotations
  3. Add the springfox-boot-starter dependency
  4. Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces
  5. If you are using WebMvc but you don't use the @EnableWebMvc annotation yet, add this annotation.

Regular spring mvc

NOTE: Would love feedback to make this experience better

  1. Remove explicit dependencies on springfox-swagger2
  2. Add @EnableOpenApi for open API (and @EnableSwagger2WebMvc or @EnableSwagger2WebFlux for older versions)
  3. Added the springfox-oas library
  4. Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces

License

Copyright 2015 Marty Pitt - @martypitt, Dilip Krishnan - @dilipkrish, Adrian Kelly - @adrianbk,

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

License

FOSSA Status

springfox-demos's People

Contributors

adjohnson916 avatar adrianbk avatar ankitjan avatar bryant1410 avatar dependabot-preview[bot] avatar dilipkrish avatar dschulten avatar karie042 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

springfox-demos's Issues

Could not download gretty.jar (org.akhikhl.gretty:gretty:1.2.0)

when i execute "gradle tasks", there is some errors :

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':spring-java-swagger'.
> Could not resolve all dependencies for configuration ':spring-java-swagger:classpath'.
   > Could not download gretty.jar (org.akhikhl.gretty:gretty:1.2.0)
      > Could not get resource 'https://plugins.gradle.org/m2/org/akhikhl/gretty/gretty/1.2.0/gretty-1.2.0.jar'.
         > Could not GET 'https://plugins.gradle.org/m2/org/akhikhl/gretty/gretty/1.2.0/gretty-1.2.0.jar'.
            > Connect to gradleware-plugins.s3.amazonaws.com:443 [gradleware-plugins.s3.amazonaws.com/54.231.18.241] failed: Connection timed out: connect

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1 mins 20.386 secs


can anybody help me?

Swagger UI showing unnecessary things.

Hi,

I have a Yaml file containing all my api definition in OpenAPI 3.0.
My requirement is to load Swagger UI from my springboot application and I have used Springfox dependencies to do the same .
Below are the dependencies used .

                <dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>

But the below thing appears from nowhere in the UI.
How to get rid of these unnecessary things in Swagger UI?
swaggerui

@ApiImplicitParam not generating the correct type for integer

I have the following annotation:
@ApiImplicitParam(name = "limit", value = "Limit the number of users returned [1-N]", required = true, dataType = "integer", paramType = "query"),

The generated datatype (as seen in swagger-ui) is marked as undefined. What is the correct type to use for integer?

Error creating bean with name 'swagger2ControllerMapping' defined in class path resource [springfox/documentation/swagger2/configuration/Swagger2DocumentationConfiguration.class]

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'swagger2ControllerMapping' defined in class path resource [springfox/documentation/swagger2/configuration/Swagger2DocumentationConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: com.google.common.base.Optional.transform(Lcom/google/common/base/Function;)Lcom/google/common/base/Optional;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
Truncated. see log file for complete stacktrace
Caused By: java.lang.NoSuchMethodError: com.google.common.base.Optional.transform(Lcom/google/common/base/Function;)Lcom/google/common/base/Optional;
at springfox.documentation.spring.web.PropertySourcedRequestMappingHandlerMapping.mappingPath(PropertySourcedRequestMappingHandlerMapping.java:82)
at springfox.documentation.spring.web.PropertySourcedRequestMappingHandlerMapping.initHandlerMethods(PropertySourcedRequestMappingHandlerMapping.java:63)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:163)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)

swagger UI for Spring Boot API : How to add “audience” in request body for authorising “client credentials” flow

I have generated swagger UI documentation from my spring boot API, the API is secured using oauth2 client credentials grant from auth0.

The problem is that:
In the swagger configuration, I am unable to set the "audience" request body parameter while authorisation.
Thus, swagger ui is not authenticating the API.

I am following this documentation:
https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

pom.xml:

	<dependency>
	    <groupId>io.springfox</groupId>
	    <artifactId>springfox-swagger-ui</artifactId>
	    <version>2.9.2</version>  
	</dependency>
	
	<dependency>
	    <groupId>io.springfox</groupId>
	    <artifactId>springfox-swagger2</artifactId>
	    <version>2.9.2</version> 
	</dependency>

SwaggerConfig.Java:

	@Configuration
	@EnableSwagger2
	public class SwaggerConfig {                                    
	
	
	String token_endpoint = "xxxx";
	
	
		@Bean
		public Docket api() {                
		    return new Docket(DocumentationType.SWAGGER_2)          
		      .select()                                       
		      .apis(RequestHandlerSelectors.basePackage("xxxx.controller"))
		      .paths(PathSelectors.any())                     
		      .build()
		      .apiInfo(apiInfo())
		      .useDefaultResponseMessages(false)
		      .securitySchemes(Arrays.asList(securityScheme()))
		      .securityContexts(Arrays.asList(securityContext()));
		}
		
	    	
	
	
		private ApiInfo apiInfo() {
		    return new ApiInfo(
		      "xxxx API", 
		      "Some description of API.", 
		      "xxxx", 
		      "Terms of service", 
		      new Contact("xx", "xxxx", "xxxx"), 
		      "License of API", "xxxx", Collections.emptyList());
		} 
	  
		
		
	    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		    registry.addResourceHandler("swagger-ui.html")
		      .addResourceLocations("classpath:/META-INF/resources/");
		 
		    registry.addResourceHandler("/webjars/**")
		      .addResourceLocations("classpath:/META-INF/resources/webjars/");
		}
	    
	   @Bean
	    public SecurityConfiguration security() {
		   
		   
	        return SecurityConfigurationBuilder.builder()
	        	.appName("xxxx")
	            .clientId("")
	            .clientSecret("")
	            .build();
	        
	    }
	    
	    private SecurityScheme securityScheme() {
	        GrantType grantType = new ClientCredentialsGrant(token_endpoint);
	        SecurityScheme oauth = new OAuthBuilder().name("spring_oauth")
	            .grantTypes(Arrays.asList(grantType))
	            .build();
	        return oauth;
	    }
	   
	    
	
		private SecurityContext securityContext() {
	        return SecurityContext.builder()
	          .forPaths(PathSelectors.any())
	          .build();
	    }  
	    
	
	    
	}

The response is as 403 Forbidden and this is because, I am not able to provide "audience" in the request body during authorization:

"error_description": "Non-global clients are not allowed access to APIv1"

Screenshot 2019-04-23 at 16 19 30__01__01

FileUpload not working with JSON data

I tried the example https://github.com/springfox/springfox-demos/blob/be4118bb031c8dcded514c33d74cae52fc51ff08/boot-swagger/src/main/java/springfoxdemo/boot/swagger/web/FileUploadController.java

Just changed the @RequestPart String description to @requestbody Component component which should be a JSON input.

Here is the code sample
@RequestMapping(value = "/v1/component/fileupload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Component fileComplaint(
@requestbody Component component, @RequestPart MultipartFile file){
...........................
}

Here is what the swagger-ui looks like
image

Here is the request details
image
image

Here is the response details
image

Here are my questions:

  1. I'm not sure why does say image in swagger-ui. It should say "application/json" instead. How do i fix this?

  2. If you request at the request paramaters, the data i'm putting in the "component" parameter is not being sent to the back-end. It only sends the file details.

  3. How do i fix org.springframework.web.HttpMediaTypeNotSupportedException??

Any kind of help will be appreciated. I already checked out the suggestions in springfox/springfox#134 and it was of no help

Thanks,
Dheeraj

swagger-ui.html is empty incase of springmvc(3.2.x) version webapp (followed springmvc demo approach)

Hi Dilip,
I have followed your demo code for springmvc (based on 3.2.xx) version and used webjars dependency . I am able to get the json content for my controllers when I use /context-root/v2/api-docs.

But If I am using /context-root/swagger-ui.html , all I am getting is an empty page with a link to swagger homepage and 2 text boxes and an explore link.

Not sure what I am missing here? Could you please guide me on how to configure the swagger-ui similar to PetStore example of springBoot app incase of a springmvc application.

Thanks a ton in advance.

Adding an example for JSR 303

Where is the best place to add an example for JSR 303?
Simply add it to the existing CategoryController/HomeController or set up a separate Controller/Model for this?

Basic Auth & Security Schemes

Hi,

Are the security schemes working on these test apps? I can see that the user docket has only read only access and is set to Basic Auth, so shouldn't a user be prevented from invoking the POST createUser endpoint?

I have run boot-swagger & spring-java and on each demo was able to create and delete users.

Thanks
Tom

@SwaggerDefinition does not work

I am integrating swagger annotation and ui for my service (spring boot App). I want to override some of the Swagger Properties like Contact Email, API Version, BaseURL.

I see we have @SwaggerDefinition Annotation present, but the changes do not show up on the UI or the json spec.

If we have support for this, please provide a demo for the same.

Swagger UI - POST a multipartfile

Hi all,
I've implemented a REST API in Java and one of the POST request accepts a file sent in the body. Everything works OK if I call using this curl:
curl -F "[email protected]" localhost:8080/index

The problem is that I'm not able to get the same curl through swagger-ui.
This is my snippet code (following the springfox-demos):

 @RequestMapping(value = "/index", method = RequestMethod.POST, consumes={ MediaType.MULTIPART_FORM_DATA_VALUE })
     public ResultIndex index(@RequestPart MultipartFile file)

And this produces the following curl on the swagger-ui:
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: */*' {"type":"formData"} 'http://localhost:8080/index'

What should I change/add in my code?
Thanks!

org.springframework.beans.factory.UnsatisfiedDependencyException

Hi,
I created a simple REST API and added a SwaggerConfig.

REST API is as simple as

	@RequestMapping(value="/demoGet")
	public String demoGet() {
		
		return "hello";
	}

SwaggerConfig is

public class SwaggerConfig {
    @Bean
    public Docket demoApi() {
    	System.out.println("docket");
        return new Docket(DocumentationType.SWAGGER_2)
                .select()                           
                .apis(RequestHandlerSelectors.basePackage("org.pjmasks.demo.application.controller"))
                .paths(regex("/demo.*"))
                .build()
                .apiInfo(apiInfo());
    }
	
    private ApiInfo apiInfo() {
    	return new ApiInfoBuilder()
                .title("Springfox MrBurns API")
                .description("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum " +
                        "has been the industry's standard dummy text ever since the 1500s, when an unknown printer "
                        + "took a " +
                        "galley of type and scrambled it to make a type specimen book. It has survived not only five " +
                        "centuries, but also the leap into electronic typesetting, remaining essentially unchanged. " +
                        "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum " +
                        "passages, and more recently with desktop publishing software like Aldus PageMaker including " +
                        "versions of Lorem Ipsum.")
                .termsOfServiceUrl("http://springfox.io")
                .contact(apiContact())
                .license("Apache License Version 2.0")
                .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")
                .version("2.0")
                .build();
    }
    
    private Contact apiContact() {    	
    	Contact contact = new Contact("abc", "def", "xyz");
    	return contact;
    }

POM.xml has both springfox-swagger2 2.6.1 and springfox-swagger-ui 2.6.1.

I got this error:


org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'swagger2Controller': Unsatisfied dependency expressed through field 'mapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceModelToSwagger2MapperImpl': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl] from ClassLoader [sun.misc.Launcher$AppClassLoader@764c12b6]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
	at org.pjmasks.demo.DemoRestApplication.main(DemoRestApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceModelToSwagger2MapperImpl': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl] from ClassLoader [sun.misc.Launcher$AppClassLoader@764c12b6]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:262) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1198) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	... 19 common frames omitted
Caused by: java.lang.IllegalStateException: Failed to introspect Class [springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl] from ClassLoader [sun.misc.Launcher$AppClassLoader@764c12b6]
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:659) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:556) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:541) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:245) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	... 31 common frames omitted
Caused by: java.lang.NoClassDefFoundError: io/swagger/models/Contact
	at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_101]
	at java.lang.Class.privateGetDeclaredMethods(Unknown Source) ~[na:1.8.0_101]
	at java.lang.Class.getDeclaredMethods(Unknown Source) ~[na:1.8.0_101]
	at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:641) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
	... 34 common frames omitted
Caused by: java.lang.ClassNotFoundException: io.swagger.models.Contact
	at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_101]
	at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_101]
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_101]
	at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_101]
	... 38 common frames omitted

Is there any other dependencies that I need to add? I have tried adding swagger-core dependencies but same error.

springboot-swagger UI doesn't work

Hi, I am trying out swagger2 with springboot 1.1.5. I got json end point working but I can't get swagger-ui.html endpoint working. Not sure what is underlaying issue here. Here is my swagger config file.

@EnableSwagger2 //Enable swagger 2.0 spec
//There is no @configuration here, even though it works, well at least json
public class SwaggerConfig {

@Autowired
private TypeResolver typeResolver;

@bean
public Docket dataResourceAPI() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("xAPI")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(commonAPIPaths())
.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()
//.securityContexts();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("REST API")
.description("swagger")
.termsOfServiceUrl("asdafsd")
.contact("abcd.com")
.license("License Version 2.0")
.licenseUrl("https://comming/soon/LICENSE")
.version("2.0")
.build();
}

private Predicate commonAPIPaths() {
return or(
regex("/v1/api/."),
regex("/v2/api/.
")
);
}
}

My main Application class is:
@componentscan(basePackages = "com.x.y")
@EnableAutoConfiguration(exclude = { EmbeddedServletContainerFactory.class })
@configuration
@EnableWebMvc
@EnableAsync
@EnableSwagger2
@ImportResource(value = { "classpath:springmvc-resteasy.xml" })
public class Application implements AsyncConfigurer, DisposableBean {
...
}

There is one more additional config class:

@configuration
public class AdditionalConfig extends WebMvcConfigurerAdapter {

@OverRide
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

//converters.add(ScalaObjectMapper);
super.configureMessageConverters(converters);
converters.add(customJackson2HttpMessageConverter());

}
}

[fix #66] springfox WARN

springfox.documentation.spring.web.readers.parameter.ParameterDataTypeReader.apply - Trying to infer dataType java.util.List<demo.model.BranchBank>

Documentation - basePath how to use?

Another beginner question .. searched but could not find any documents or examples.

By default the basePath in the swagger-ui is always shown as swagger-java since i am using that project. How do i change that to the right basePath?

I can see that Documentation has a basePath setting. But could not figure out how to link Documentation to Docket or other class?

Thanks in advance.

springfox 2.5 with jdk1.8 and spring 4

Hi,

I am using springfox 2.5 with jdk1.8 and spring4, i get following errors, please suggest.

org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [springfox] in web application [/test] threw load() exception
java.lang.ClassNotFoundException: org.springframework.plugin.core.Plugin
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)

Not able to run/configure the swagger with springfox in grails 3 application.

Hi Team
I am new to the springfox and grails 3. I am trying to generate the swagger documentation for controllers in the grails 3 applicaiton. But i am not able to run the application.
When we configure the configuration class to enable the swagger ,still is it necessary to right the annotations on the controllers?
Can it create some default documentation without using the annotations in the controllers code?
Please find the link to the project i am trying to run.

Implementing client credentials grant for Spring fox

I have a working spring mvc swagger implementation (the old version prior to spring fox) and I am looking at updating it to spring fox.

I have a working client credentials version using some custom code. Is client credentials grant supported? I saw some talk on the issues page that said it would be in the future (has the future happened yet).

I want to update my version of this with the new spring fox. Any examples?

How to turn off swagger-ui?

For example, the project has been completed and launched, but we do not want swagger-ui to be shown to users. How do you do it?
Is there another way besides filter?

api docs not listing paths when i use @PathVariable annotation in my controller

I am using spring boot application with below springfox dependencies.

compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
@RequestMapping(value = "/{orderNumber}/extend",
            method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
public ResponseEntity<?> extend(
            @PathVariable String orderNumber,
            HttpServletRequest httpRequest,
            @Valid @RequestBody(required = false) ExtendRequest request,
            BindingResult bindingResult)
             { }

As i mentioned above if i use @PathVariable for orderNumber then i couldn't see paths in api docs (http://localhost:8130/modifications/v2/api-docs)

After debug and removed the @PathVariable then i can able to see the paths in api-docs.

@dilipkrish Please provide your valuable inputs on this issue?

During server startup noticed below exception: but still server started.

{
    "@timestamp": "2018-07-10T15:11:31.170-05:00",
    "@version": 1,
    "level": "ERROR",
    "level_value": 40000,
    "logger_name": "springfox.documentation.spring.web.scanners.ApiDescriptionReader",
    "message": "Skipping process path[/{orderNumber}/extend], method[pickupExtend] as it has an error.",
    "stack_trace": "com.google.common.util.concurrent.ExecutionError: java.lang.NoSuchMethodError: org.springframework.web.bind.annotation.PathVariable.name()Ljava/lang/String;
	at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2212)
	at com.google.common.cache.LocalCache.get(LocalCache.java:4053)
	at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4057)
	at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4986)
	at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4992)
	at springfox.documentation.spring.web.scanners.CachingOperationReader.read(CachingOperationReader.java:57)
	at springfox.documentation.spring.web.scanners.ApiDescriptionReader.read(ApiDescriptionReader.java:70)
	at springfox.documentation.spring.web.scanners.ApiListingScanner.scan(ApiListingScanner.java:134)
	at springfox.documentation.spring.web.scanners.ApiDocumentationScanner.scan(ApiDocumentationScanner.java:71)
	at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.scanDocumentation(DocumentationPluginsBootstrapper.java:101)
	at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:167)
	at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:173)
	at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:51)
	at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:346)
	at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:149)
	at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:112)
	at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:874)
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544)
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174)
	at com.tgt.post.order.purchase.app.PostOrderPurchaseApp.main(PostOrderPurchaseApp.java:37)
Caused by: java.lang.NoSuchMethodError: org.springframework.web.bind.annotation.PathVariable.name()Ljava/lang/String;
	at springfox.documentation.spring.web.readers.parameter.ParameterRequiredReader.isRequired(ParameterRequiredReader.java:92)
	at springfox.documentation.spring.web.readers.parameter.ParameterRequiredReader.apply(ParameterRequiredReader.java:61)
	at springfox.documentation.spring.web.plugins.DocumentationPluginsManager.parameter(DocumentationPluginsManager.java:106)
	at springfox.documentation.spring.web.readers.operation.OperationParameterReader.readParameters(OperationParameterReader.java:103)
	at springfox.documentation.spring.web.readers.operation.OperationParameterReader.apply(OperationParameterReader.java:75)
	at springfox.documentation.spring.web.plugins.DocumentationPluginsManager.operation(DocumentationPluginsManager.java:120)
	at springfox.documentation.spring.web.readers.operation.ApiOperationReader.read(ApiOperationReader.java:73)
	at springfox.documentation.spring.web.scanners.CachingOperationReader$1.load(CachingOperationReader.java:50)
	at springfox.documentation.spring.web.scanners.CachingOperationReader$1.load(CachingOperationReader.java:48)
	at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3628)
	at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2336)
	at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2295)
	at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2208)
	... 25 common frames omitted
",
    "thread_name": "main"
}

Confusing Documentation

The documentation and demo's are very confusing and hard to build/deploy. Are there any simple example projects out there for people to get started?

If possible, instead of abstracting everything away with Springboot, can we see some examples using a simple Spring-MVC project (ie Hello World)

boot-swaggerSwagger docs endpoint: (http://localhost:8080/springfox/v2/api-docs) gives a 404

boot-swagger demo's Swagger docs endpoint: (http://localhost:8080/springfox/v2/api-docs) gives a 404.

Other urls:

I found this out as I have the same problem in my own app.
Note that boot-static-docss Swagger docs endpoint does work.

Springmvc tests Swagger2

While the swagger2 looks great, i am looking for some mvc integration tests by injecting the dependencies of swagger2... Any demo already done?

Also i noticed, after integrating with spring mvc , my integration tests are failing and my maven build runs out of heap size

springmvc 4.1.9.RELEASE can't work No operations defined in spec!

http://localhost:8080/jeesite/v2/api-docs
http://localhost:8080/jeesite/swagger-ui.html

all url ok,but notice below:

No operations defined in spec!

{"swagger":"2.0","info":{"description":"Swagger在线使用教程","version":"1.0.1","title":"JeeSite工作室 Swagger教程","termsOfService":"http://www.jeesite.com","contact":{"name":"长春叭哥","url":"http://www.jeesite.com","email":"[email protected]"},"license":{"name":"LICENSE","url":"LICENSE URL"}},"host":"localhost:8080","basePath":"/jeesite"}

Tags not working properly

Hi,

I have added springfox-swagger2 (version: '2.5.0') and springfox-swagger-ui (version: '2.5.0') dependency in gradle, added @EnableSwagger2. Below is my Swagger configuration file:

@Configuration
public class SwaggerDocumentationConfig {

    ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("Test Information")
            .description("Test Information")
            .license("Apache 2.0")
            .licenseUrl("http://example.com")
            .termsOfServiceUrl("http://example.com/contact")
            .version("0.0.1")
            .contact(new Contact("","", "[email protected]"))
            .build();
    }

    @Bean
    public Docket customImplementation(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                    .apis(RequestHandlerSelectors.basePackage("com.abc.com"))
                    .build()
                .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
                .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
                .tags(new Tag("TestInfo", "All apis relating to test"))
                .apiInfo(apiInfo());
    }

}

Below is the sample webservice:

@ApiOperation(value = "update test doc status",tags={ "TestInfo",})
	@RequestMapping(value = "/getTestStatus/{testId}", method = RequestMethod.GET, headers = "Accept=application/json")
	public TestStatus getTestStatusForTestId(@PathVariable("testId") long testId){
		System.out.println("TestController::getTestStatusForCustId - testId=" + testId);
		TestStatus statusToReturn = new TestStatus();
		List<TestDTO> testStatus = getTestStatus();
		for (TestDTO currentStatus : testStatus) {
			if (currentStatus.geTestId() == testId) {
				statusToReturn.setId(currentStatus.getId());
				statusToReturn.setTestId(currentStatus.getTestId());
				statusToReturn.setStatus(currentStatus.getStatus());
				break;
			}
		}		
		return statusToReturn;
	}

In my rest services I have added TestInfo tags in @ApiOperation. But the apis are not getting listed in Swagger UI.
Note:

  1. api-docs json has TestInfo tags related rest services apis values present in path property.
  2. Rest webservices class is manually created.

Please suggest what i am missing.

Swagger2 with springRESTAPI

I have a Spring Rest controller and its NOT spring boot application. Its just a REST API Project. I want to integrate swagger2 in my project. I tried all the examples in Net and in demo but with no luck. When i try to execute http://localhost:8085/context/swagger-ui.html i get 404 error. Please find my confugration below and let me know if there is any discrepencies. Any help is highly appreciated.

jars - under /WEB-INF/lib
google-collections-1.0.jar
springfox-core-2.2.2.jar
springfox-schema-2.2.2.jar
springfox-spi-2.2.2.jar
springfox-spring-web-2.2.2.jar
springfox-staticdocs-2.2.2.jar
springfox-swagger-common-2.2.2.jar
springfox-swagger-ui-2.2.2.jar
springfox-swagger2-2.2.2.jar

my swagger config class -

@EnableSwagger2
public class SwaggerConfiguration {

}

my springconfig class

@EnableWebMvc
@ComponentScan(basePackageClasses = controller.class)
@Import(SwaggerConfiguration.class)
public class SpringConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

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

and Application Initializer class

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{controller.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/*"};
    }
}

I have my Rest configuration in /WEB-INF/spring/rest-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 <context:component-scan base-package="com.xx.yy.zz." />
 <mvc:annotation-driven />
  </beans>

I can access my rest urls but not swagger-ui.html .

Please let me know what i am missing here?

authorization - httpauth. How to do it right?

This is snippet of my code from SwaggerConfiguration:

AuthorizationScope[] authScopes = new AuthorizationScope[1];
    authScopes[0] = new AuthorizationScopeBuilder()
            .scope("read")
            .description("Read Access")
            .build();

    SecurityReference securityReference = SecurityReference.builder()
            .reference("test")
            .scopes(authScopes)
            .build();

    ArrayList<SecurityReference> reference = new ArrayList(1);
    reference.add(securityReference);

    ArrayList<SecurityContext> securityContexts = new ArrayList(1);
    securityContexts.add(SecurityContext.builder().securityReferences(reference).build());

    ArrayList<SecurityScheme> auth = new ArrayList(1);
    auth.add(new BasicAuth("test"));

    return new Docket(DocumentationType.SWAGGER_2)
        .securitySchemes(auth)
        .securityContexts(securityContexts)
        .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) 
        .paths(regex("/API/v2/.*"))
        .build()
        .pathMapping("/")
        .protocols(protocols)
        .apiInfo(metadata());
}

When I use the generated json or directly access swagger-ui and try to hit the URL, the basic authentication used above does not seem to work. Does not ask for credentials and also just keeps returning 0 although the URL is correct.

Any hints on where this is going wrong?

Change name and description for relation of entity

Hello,

I’m using springbox swagger 2.9.2 and spring-data-rest. When i override the name and description (with @Api(tags = ...) ) for repository and entity, it’s works. But if the entity has a relation (join), its API documentaion doesn’t appear in the same “tags”.

Do you have the solution in order to fix that ?

Thank you.

Question about springfox 2.0 and swagger ui?

So i changed over to springfox 2.0 and am trying to get the spring-boot demo working.

I have everything needed eg petstore etc. I put the contents of the dist folder from swagger ui in src/main/webapp/swagger folder and in the index.html I changed the line url = "http://petstore.swagger.io/v2/swagger.json"; to url = "http://localhost:8080/api-docs"; so when I run it and go to http://localhost:8080/swagger/index.html shouldn't it display the api?

On another note in before when configuring swagger you could add ".includePatterns()" but I don't see this in the new version so how does it read in endpoints to include?

Hope this makes sense and if it doesn't I apologise, I've only been using swagger and related libraries for a week and a lot of what I have figured out has just been trial and error.

Could not download dependencies because of peer not authenticated error

Hi!

I just cloned demo repo and launched ./gradlew idea. I got error:

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'springfox-demos'.

Could not resolve all dependencies for configuration ':classpath'.
Could not download xercesImpl.jar (xerces:xercesImpl:2.9.1)
> Could not get resource 'https://jcenter.bintray.com/xerces/xercesImpl/2.9.1/xercesImpl-2.9.1.jar'.
> Could not GET 'https://jcenter.bintray.com/xerces/xercesImpl/2.9.1/xercesImpl-2.9.1.jar'.
> peer not authenticated

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 5.525 secs

springfox-swagger-2.6.1 cannot find swagger-resources when run outside of spring boot 1.3

Hi,
I am using springfox-swagger2 -2.6.1 with springboot 1.3. Now when I run the application and try to see swagger dynamic documentation through web browser using http://localhost:8080//swagger-ui.html, I am not getting expected output, instead of that I am getting UI error -as mentioned below

GET http://localhost:8080/webjars/springfox-swagger-ui/images/favicon-32x32.png 405 ()

GET http://localhost:8080/webjars/springfox-swagger-ui/springfox.js 405()

as suggested by other post I have added WebConfig as well

@configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@OverRide
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}

but still facing the same issue.

Any help is greatly appreciated

swagger-ui.html can't be visited with Spring Security

@dilipkrish After updating Swagger from 2.7.0 to 2.8.0, I faced the same issue @evser.

application.yml configuration:

security:
    basic:
        enabled: true
        path: /swagger-resources/**,/v2/api-docs
    user:
        name: admin
        password: 123456

When I visit swagger-ui.html,2.7.0 works well,but 2.8.0 alerts me:
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/.

If I remove /swagger-resources/** from the configuration file, everything works well!What's the problem?Is v2.8.0 changed the directory?

Download compiled jar file

I want to use this project from the command line. However, I don't have a Java development environment on my machine. I'm not able to find a prebuilt jar file here. Is it available for download somewhere? Thanks!

400 error with swagger-ui.html

I am using spring boot app to build the swagger documentation using below dependency.
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'

I can able to access http://localhost:8130/{contextPath}/v2/api-docs sucessfully
When i try to access swagger ui http://localhost:8130/{contextPath}/swagger-ui.html throwing 400 error.

response
{"message":"Could not find acceptable representation"}

OAuth login for full-petstore-api no working

I just downloaded the code as of today and tried out the (full-petsotre-api(/v2/api-docs?group=full-petstore-api)) pull down

when I select the Authorize button, I see the Available authorizations dialog come up. I select one and select Authorize.

the url changes to http://petstore.swagger.io/api/oauth/dialog?response_type=token&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fspringfox%2Fwebjars%2Fspringfox-swagger-ui%2Fo2c.html&realm=pets&client_id=abc&scope=write%3Apets%2Cread%3Apets%2CvendorExtensions&state=petstore_auth

then I see Http Error 404
Problem accessing /api/oauth/dialog. Reason: Not Found

All I did was build and run as per the example. Is something missing?

Spring XML demo confusing

Hi Dilip,

I am yet to be a fan of Springfox :)

On multiple occasions, I have tried following the demo but they lag in clarity. I am willing to add a better demo to showcase Spring (v4.2) XML + Springfox(v2) working. I am wondering, if you would like something like this included as functional demo.

Thanks

boot-swagger bugs

1.CategoryController
method search should be @PathVariable(value = "someEnum") instead of @RequestParam(value = "someEnum") .or it will be get an 405 method 'GET' not support ,even if you change to POST
2.@EnableSwagger to Enable swagger 1.2 spec ,but the api urls of 1.2 all are 404,
3.UserController
1.api/user/createWithArray
{ "timestamp": 1473063607454, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.beans.BeanInstantiationException", "message": "Failed to instantiate [[Lspringfox.petstore.model.User;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lspringfox.petstore.model.User;.<init>()", "path": "/springfox/api/user/createWithArray" }
2./api/user/createWithList
{ "timestamp": 1473063612221, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.beans.BeanInstantiationException", "message": "Failed to instantiate [java.util.List]: Specified class is an interface", "path": "/springfox/api/user/createWithList" }
3./api/user/login?username=a&password=a
It can be visit directly,but test the api ,there is
Response Body no content Response Code 0 Response Headers { "error": "no response from server" }

Cannot constractor 'documentationPluginsBootstrapper'

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'documentationPluginsBootstrapper' defined in URL [jar:file:/E:/WS/HT_WS/apache-tomcat-8.0.21/webapps/monster-carbarn-api/WEB-INF/lib/springfox-spring-web-2.0.3.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [java.util.List]: : No qualifying bean of type [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] found for dependency [collection of org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1071) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ... 24 more

My Swagger configuration
`@EnableSwagger2
public class SwaggerConfig {

@Bean  
public Docket customDocket () {
    Docket docket = new Docket( DocumentationType.SWAGGER_2 );
    docket.apiInfo ( apiInfo () );
    return docket;  
} 

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo ( 
            "My Apps API Title", 
            "My Apps API Description", 
            "My Apps API Version", 
            "My Apps API terms of service", 
            "My Apps API Contact Email", 
            "My Apps API Licence Type",
            "My Apps API License URL" );
    return apiInfo;
}

}`

@EnableWebMvc
@componentscan(basePackages = { "com.xxx.api" })
@import(SwaggerConfig.class)
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

@Override
public void addViewControllers( ViewControllerRegistry registry ) {
    registry.addViewController ( "/**" );
    registry.setOrder ( Ordered.LOWEST_PRECEDENCE );
}

@Override
public void addResourceHandlers( ResourceHandlerRegistry registry ) {
    registry.addResourceHandler ( "swagger-ui.html" ).addResourceLocations ( "classpath:/META-INF/resources/" );

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

}

HashMap<String,Object> Does not show up in parameters

Hi,
I have an API Model Class that I use as controller input. When I generate swagger ui by sprinfox, all fields except for a HashMap field are shown as text boxes under Parameters. I was expecting to show it. Am I missing something or can't swagger show HashMap fields like others under Parameters?

My controller method

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<XObject> createTemplate(@ModelAttribute @Valid @RequestBody XObject obj) 

API Model Class

@ApiModel(value = "XObject")
public class XObject {
    @NotNull
    @ApiModelProperty(value = "Prm 1", position = 0, required = true)
    private Integer abc1;
     @ApiModelProperty(value = "Parameter Map",dataType ="java.util.HashMap" ,position = 1, required = false)
    private HashMap<String, Object> myMap;

    public XObject() {
    }

    public Integer getAbc1() {
        return abc1;
    }
    public void setAbc1(Integer a) {
        this.abc1= a;
    }

    public HashMap<String, Object> getMyMap() {
        return myMap;
    }

    public void setMyMap(HashMap<String, Object> myMap) {
        this.myMap= myMap;
    }
}

Swagger2 with Spring MVC

I have a Spring REST controller and I am trying to integrate Swagger2 into it. It is NOT a Spring Boot application. I am not trying to integrate swagger-ui as of now, but just trying to generate the JSON docs when I access http://localhost:8080/SwaggerTestProject/v2/api-docs I get a 404 error.

I have also looked at the Springfox demos and issue #14 , but to no avail.
Please find my Java files and my configuration files below.

jars under WEB-INF/lib
springfox-core-2.5.0
springfox-schema-2.5.0
springfox-spi-2.5.0
springfox-spring-web-2.5.0
springfox-swagger2-2.5.0
springfox-swagger-common-2.5.0

SwaggerConfig.java

package com.swaggertest.config;
@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket api(){
		return new Docket(DocumentationType.SWAGGER_2)
				.select()
				.apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any())
				.build()
				.apiInfo(apiInfo());
	}
	
	private ApiInfo apiInfo(){
		return new ApiInfoBuilder()
				.title("TITLE")
				.description("DESCRIPTION")
				.version("VERSION")
				.license("LICENSE")
				.build();
	}	
}

TestController.java

package com.swaggertest.controller;
@Controller
@RequestMapping("/test")
public class TestController {

	@RequestMapping(value = "/testmethod", method = RequestMethod.GET , produces="application/json")
	public ResponseEntity<?> testMethod(){
		return new ResponseEntity<>("Hello world", HttpStatus.OK);
	}
}

My Spring configuration in /WEB-INF/spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<context:component-scan base-package="com.swaggertest.controller" />
	<context:component-scan base-package="com.swaggertest.config" />

	<mvc:annotation-driven />

</beans>

I am not sure if I need a class which extends the WebMvcConfigurerAdapter.

I have configured my project as a Dynamic Web Project in Eclipse. I have configured Apache Tomcat 7.0.70 in Eclipse and I run my project by right-clicking on the project and selecting Run on Server.
Again I am not trying to set up Swagger UI but just want to generate the JSON docs of my APIs.

I believe I am missing something really simple. Any help will be appreciated. Thanks in advance!

How do I log all validation errors rejected by swaggerfox?

How do I log all validation errors rejected by SwaggerFox? E.G. not passing in a value or not passing in a value from an EnumType. I would prefer a call back function that is passed;

  1. Input json
  2. response validation errors json

Inside this method I would like to log the request and response. I also want to trigger some custom logic.

Is this possible?

How to hide Model Schema or display an example rather than Model Schema

Hi

I'm using springfox with spring-boot to generate swagger documentation. Here are my maven dependencies.

io.springfox springfox-swagger-ui 2.4.0
	<dependency>
		<groupId>io.springfox</groupId>
		<artifactId>springfox-swagger2</artifactId>
		<version>2.4.0</version>
	</dependency>

When I open swagger-ui for the generated API. I see the following screen.
image

As you can see it shows this huge model schema. I do not want to see this. I want one of these things to happen:

  1. Hide entire model schema
  2. Display an example rather than Model Schema
  3. Display model schema depending on the response.

Any suggestions or help will be appreciated.

Thanks,
Dheeraj

No security scope definition generated

I've launched springfox-demos:boot-swagger project, copy-pasted the generated JSON from http://localhost:8080/springfox/oai/api-docs?group=user-api into Swagger Editor (via File > Paste JSON menu), and got the following error

errors screenshot from 2017-03-27 03-24-21

It states:

code: "UNRESOLVABLE_REFERENCE"
message: "Security scope definition could not be resolved: read"
level: 900
type: "Swagger Error"

Here's the relevant JSON

...
"paths":{"/api/user":{"post":
...
"security":[{"test":["read"]}]
}},
...
"securityDefinitions":{"test":{"type":"basic"}},
...

And YAML

...
paths:
  /api/user:
    post:
...
      security:
        - test:
            - read
...
securityDefinitions:
  test:
    type: basic
...

This issue is reproducible for BasicAuth and ApiKey authentication types.

Property Key Value not working

Property values are not being substituted.
So I am attempting to debug. However, I cannot find the point in the swagger code where the substitution is occurring. If you point me to this location, I can chase it further and see what the issue is.
Spring 4.2
XML Configuration
Gradle

(Specifically for ApiOperation.notes)

Thanks,

Tim

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.