EzDevInfo.com

swagger-ui

Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API. Swagger | The World's Most Popular Framework for APIs.

How to describe a model i Swagger for an array with simple objects?

I have a REST services to document, some of them accepts simple array like:

[ { "name":"a" }, { "name":"b" }, { "name":"c" } ]

how to describe this in Swagger model section ? I can only create 'named array' like model { properties: { "arr": { "type":"array", ......

but it describes data like this:

"arr": [ { "name":"a" }, { "name":"b" }, { "name":"c" } ]


Source: (StackOverflow)

Swagger isn't smart enough to handle anonymous types (such as maps)

I'm using enunciate to generate Swagger documentation for a REST API. One of my legacy beans contains a Map, and Swagger complains about this:

[INFO] --- maven-enunciate-plugin:1.27:docs (default) @ foo-api ---
[INFO] initializing enunciate.
[INFO] invoking enunciate:generate step...
[WARNING] Validation result has errors.
/.../rest/BarBean.java:170: [swagger] Swagger isn't smart enough to handle anonymous types (such as maps).
   public HashMap<String, BazBean> getBazBeans() {

Are there any annotations I can drop into the bean class so that Swagger can handle this?

Barring that, is there a way to tell Swagger to simply ignore the field or the whole class? I know that Swagger ignores classes without the @XmlRootElement annotation, but BazBean is tragically used in another endpoint that accepts XML.


Source: (StackOverflow)

Advertisements

Swagger API: how to make fields required where only one parameter is required?

I have a series of parameters in swagger like this

                    "parameters": [
                    {
                        "name": "username",
                        "description": "Fetch username by username/email",
                        "required": false,
                        "type": "string",
                        "paramType": "query"
                    },
                    {
                        "name": "site",
                        "description": "Fetch username by site",
                        "required": false,
                        "type": "string",
                        "paramType": "query"
                    },
                    {
                        "name": "survey",
                        "description": "Fetch username by survey",
                        "required": false,
                        "type": "string",
                        "paramType": "query"
                    }
                ],

One parameter MUST be filled out but it doesn't matter which one, the others can be left blank. Is there a way to represent this in Swagger?


Source: (StackOverflow)

How to change the path of swagger-ui in spring-mvc

How can I change the path of swagger-ui so that it is not loaded on / but at /docs/ The simple solution recommended in some blogs would be to unpack swagger-spring-mvc-ui sources in webapps dir. But I search for a elegant solution where the webjar swagger-spring-mvc-ui is a dependency like all others.


Source: (StackOverflow)

Sort API methods in Swagger-UI

I cannot find any working example, how to achieve the following: I want my API methods in the Swagger-UI sorted either by methods (GET-POST-PUT-DELETE) OR/AND alphabetically.

So far, all methods are displayed in a random order, even not in the order given my source code.

I use Jax-RS + Jersey 1.

Sorting using the position attribute of @ApiOperation is not an option for me, as there are too many methods and the API is still extending, so I would need to update all if there is a new one.

Any hints?


Source: (StackOverflow)

SwaggerSpringMvcPlugin not working on Spring MVC

I am using the following components in my REST back-end project:

  • Spring MVC: 4.1.2.RELEASE (latest)
  • Hibernate4 Object Mapper: 2.4.3 (latest)
  • Swagger: 0.9.1 (latest)
  • Javaee-web-api: 7.0 (servlet 3.1)

I'm using XML based bean configuration and I was able to get the basic setup with Swagger up and running, using the following in Spring XML Configuration file:

 <mvc:annotation-driven/> <!-- Required so swagger-springmvc can access spring's RequestMappingHandlerMapping  -->

 <bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

I then cloned the Swagger-UI GIT repo from https://github.com/wordnik/swagger-ui and copied of the dist folder to my /webapp/docs folder. After doing so I was able to use the JS based UI on the following URL:

http://localhost:9090/docs/index.html (works so far).

The problem is that none of the try it out buttons worked, which can be used to interact with your REST API using JSON directly. The reason that it did not work is that it did not take the correct base url path to talk to my controllers:

http://localhost:9090/rest/addresses (actual controller location)
http://localhost:9090/addresses (swagger's attempt to talk to the API)

After some research online I found out that I probably better go for the more flexible approach using SwaggerSpringMvcPlugin as documented on https://github.com/martypitt/swagger-springmvc.

This is my swagger configuration class file:

@Configuration
@EnableSwagger
public class MySwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    @Bean
    public SwaggerSpringMvcPlugin customImplementation(){
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .includePatterns(".*");
    }
}

This is my full spring mvc xml file:

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

    <context:component-scan base-package="be.exampley.backend.web.rest"/>

    <bean id="hibernateAwareObjectMapper" class="be.example.backend.util.HibernateAwareObjectMapper"/>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
                  p:prettyPrint="true"
                  p:supportedMediaTypes-ref="supportedMediaTypes"
                  p:objectMapper-ref="hibernateAwareObjectMapper"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <util:list id="supportedMediaTypes">
        <value>application/json</value>
        <value>text/plain</value>
    </util:list>

    <context:annotation-config/>

    <mvc:default-servlet-handler/>

    <context:property-placeholder location="classpath:swagger.properties"/>

    <bean name="swaggerConfig" class="be.example.backend.configuration.MySwaggerConfig"/>

</beans>

An extract of the relevant section from my web.xml file:

<servlet>
    <servlet-name>restServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/mvc-rest-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>restServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

This is my swagger.properties file, which is not taken into account at all for some reason.

documentation.services.basePath=/rest/
documentation.services.version=2.0

The stacktrace I get during application startup:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySwaggerConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void be.example.backend.configuration.MySwaggerConfig.setSpringSwaggerConfig(com.mangofactory.swagger.configuration.SpringSwaggerConfig); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mangofactory.swagger.configuration.SpringSwaggerConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List com.mangofactory.swagger.configuration.SpringSwaggerConfig.handlerMappings; 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: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:798)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:444)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:789)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1341)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1334)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:497)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:163)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.server.Server.start(Server.java:387)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:354)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.runner.Runner.run(Runner.java:509)
    at org.eclipse.jetty.runner.Runner.main(Runner.java:557)
...
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: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1261)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:961)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1081)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1006)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:600)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:798)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:444)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:789)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1341)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1334)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:497)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:163)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
    at org.eclipse.jetty.server.Server.start(Server.java:387)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:354)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.runner.Runner.run(Runner.java:509)
    at org.eclipse.jetty.runner.Runner.main(Runner.java:557)

I read somewhere that the No qualifying bean of type org...RequestMappingHandlerMapping trace suggests I might miss mvc:annotation-driven in my XML, but this is not the case.

I have been searching for hours now to find a solution, but failed so far. The fact that in it's basic configuration (using SpringSwaggerConfig) it's working for 90% (besides the try it out button...), makes me not want to give up on swagger just yet. It really seems very cool and is a good way of documenting your API.

So if anyone can help me out on this one, I would be very gratefull. Swagger rocks!

Kind regards, Bart


Source: (StackOverflow)

Unable to link Swagger-ui to my swagger Spring mvc project

I'm currently creating an API Rest using Eclipse, Spring Framework MVC, and I just added to my project swagger. I can access the json result of swagger but I need to add swagger ui.

Here are all my files creating for swagger-springmvc:

WebAppInitializer.java

public class WebAppInitializer implements WebApplicationInitializer {

    private AnnotationConfigWebApplicationContext ctx = null;

    @Override
    public void onStartup(final ServletContext sc) throws ServletException {

        System.setProperty("spring.profiles.active", "web");

        // Create the 'root' Spring application context
        ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringBaseWebConfiguration.class,
                SpringSwaggerConfiguration.class);

        // Manages the lifecycle
        sc.addListener(new ContextLoaderListener(ctx));
        sc.addListener(new ContextCleanupListener());

        // Spring WebMVC
        ServletRegistration.Dynamic springWebMvc = sc.addServlet("ws",
                new DispatcherServlet(ctx));
        springWebMvc.setLoadOnStartup(1);
        springWebMvc.addMapping("/ws/*");
        springWebMvc.setAsyncSupported(true);
    }

    @PreDestroy
    protected final void cleanup() {
        if (ctx != null) {
            ctx.close();
        }
    }
}

SpringSwaggerConfiguration.java

public class SpringSwaggerConfiguration {
    public static final List<String> DEFAULT_INCLUDE_PATTERNS = Arrays
            .asList(new String[]{"/com/sa/rnd/dark/resources/.*"});
    public static final String SWAGGER_GROUP = "ApiDark";
    public static final String RELATIVE_GROUP = "ApiDark";
    @Autowired
    private SpringSwaggerConfig springSwaggerConfig;

/**
 * Adds the jackson scala module to the MappingJackson2HttpMessageConverter
 * registered with spring Swagger core models are scala so we need to be
 * able to convert to JSON Also registers some custom serializers needed to
 * transform swagger models to swagger-ui required json format
 */
@Bean
public JacksonScalaSupport jacksonScalaSupport() {
    final JacksonScalaSupport jacksonScalaSupport = new JacksonScalaSupport();
    // Set to false to disable
    jacksonScalaSupport.setRegisterScalaModule(true);
    return jacksonScalaSupport;
}

/**
 * Global swagger settings
 */
@Bean
public SwaggerGlobalSettings swaggerGlobalSettings() {
    final SwaggerGlobalSettings swaggerGlobalSettings = new SwaggerGlobalSettings();
    swaggerGlobalSettings.setGlobalResponseMessages(springSwaggerConfig
            .defaultResponseMessages());
    swaggerGlobalSettings.setIgnorableParameterTypes(springSwaggerConfig
            .defaultIgnorableParameterTypes());
    return swaggerGlobalSettings;
}

/**
 * API Info as it appears on the swagger-ui page
 */
private ApiInfo apiInfo() {
    return new ApiInfo(
            "Swagger Spring MVC for Dark Api",
            "Sample application demonstrating how to use swagger-springmvc in a no-XML environment.",
            "http://en.wikipedia.org/wiki/Terms_of_service",
            "michael@laccetti.com", "Apache 2.0",
            "http://www.apache.org/licenses/LICENSE-2.0.html");
}

/**
 * Configure a SwaggerApiResourceListing for each swagger instance within
 * your app. e.g. 1. private 2. external apis Required to be a spring bean
 * as spring will call the postConstruct method to bootstrap swagger
 * scanning.
 *
 * @return
 */
@Bean
public SwaggerApiResourceListing swaggerApiResourceListing() {
    // The group name is important and should match the group set on
    // ApiListingReferenceScanner
    // Note that swaggerCache() is by DefaultSwaggerController to serve the
    // swagger json
    final SwaggerApiResourceListing swaggerApiResourceListing = new SwaggerApiResourceListing(
            springSwaggerConfig.swaggerCache(), SWAGGER_GROUP);

    // Set the required swagger settings
    swaggerApiResourceListing
            .setSwaggerGlobalSettings(swaggerGlobalSettings());

    // Supply the API Info as it should appear on swagger-ui web page
    swaggerApiResourceListing.setApiInfo(apiInfo());

    // Use the default path provider
    swaggerApiResourceListing.setSwaggerPathProvider(springSwaggerConfig
            .defaultSwaggerPathProvider());

    // Global authorization - see the swagger documentation
    swaggerApiResourceListing.setAuthorizationTypes(authorizationTypes());

    // Sets up an auth context - i.e. which controller request paths to
    // apply global auth to
    swaggerApiResourceListing
            .setAuthorizationContext(authorizationContext());

    // Every SwaggerApiResourceListing needs an ApiListingReferenceScanner
    // to scan the spring request mappings
    swaggerApiResourceListing
            .setApiListingReferenceScanner(apiListingReferenceScanner());
    return swaggerApiResourceListing;
}

@Bean
/**
 * The ApiListingReferenceScanner does most of the work.
 * Scans the appropriate spring RequestMappingHandlerMappings
 * Applies the correct absolute paths to the generated swagger resources
 */
public ApiListingReferenceScanner apiListingReferenceScanner() {
    ApiListingReferenceScanner apiListingReferenceScanner = new ApiListingReferenceScanner();

    // Picks up all of the registered spring RequestMappingHandlerMappings
    // for
    // scanning
    apiListingReferenceScanner
            .setRequestMappingHandlerMapping(springSwaggerConfig
                    .swaggerRequestMappingHandlerMappings());

    // Excludes any controllers with the supplied annotations
    apiListingReferenceScanner.setExcludeAnnotations(springSwaggerConfig
            .defaultExcludeAnnotations());

    //
    apiListingReferenceScanner
            .setResourceGroupingStrategy(springSwaggerConfig
                    .defaultResourceGroupingStrategy());

    // Path provider used to generate the appropriate uri's
    apiListingReferenceScanner
            .setSwaggerPathProvider(relativeSwaggerPathProvider());

    // Must match the swagger group set on the SwaggerApiResourceListing
    apiListingReferenceScanner.setSwaggerGroup(SWAGGER_GROUP);

    // Only include paths that match the supplied regular expressions
    apiListingReferenceScanner.setIncludePatterns(DEFAULT_INCLUDE_PATTERNS);

    return apiListingReferenceScanner;
}

private List<AuthorizationType> authorizationTypes() {
    final List<AuthorizationType> authorizationTypes = new ArrayList<>();
    authorizationTypes.add(new BasicAuth());
    return authorizationTypes;
}

@Bean
public AuthorizationContext authorizationContext() {
    final List<Authorization> authorizations = newArrayList();

    AuthorizationScope authorizationScope = new AuthorizationScope(
            "global", "accessEverything");

    AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
    authorizations.add(new Authorization("basic", authorizationScopes));

    AuthorizationContext authorizationContext = new AuthorizationContext.AuthorizationContextBuilder(
            authorizations).withIncludePatterns(DEFAULT_INCLUDE_PATTERNS)
            .build();

    return authorizationContext;
}

// Relative path example
@Bean
public SwaggerApiResourceListing relativeSwaggerApiResourceListing() {
    SwaggerApiResourceListing swaggerApiResourceListing = new SwaggerApiResourceListing(
            springSwaggerConfig.swaggerCache(), RELATIVE_GROUP);
    swaggerApiResourceListing
            .setSwaggerGlobalSettings(swaggerGlobalSettings());
    swaggerApiResourceListing
            .setSwaggerPathProvider(relativeSwaggerPathProvider());
    swaggerApiResourceListing
            .setApiListingReferenceScanner(relativeApiListingReferenceScanner());
    return swaggerApiResourceListing;
}

@Bean
public ApiListingReferenceScanner relativeApiListingReferenceScanner() {

    ApiListingReferenceScanner apiListingReferenceScanner = 
            new ApiListingReferenceScanner();

    apiListingReferenceScanner
            .setRequestMappingHandlerMapping(springSwaggerConfig
                    .swaggerRequestMappingHandlerMappings());

    apiListingReferenceScanner.setExcludeAnnotations(springSwaggerConfig
            .defaultExcludeAnnotations());

    apiListingReferenceScanner
            .setResourceGroupingStrategy(springSwaggerConfig
                    .defaultResourceGroupingStrategy());

    apiListingReferenceScanner
            .setSwaggerPathProvider(relativeSwaggerPathProvider());

    apiListingReferenceScanner.setSwaggerGroup(RELATIVE_GROUP);
    apiListingReferenceScanner.setIncludePatterns(DEFAULT_INCLUDE_PATTERNS);
    return apiListingReferenceScanner;
}

@Bean
public SwaggerPathProvider relativeSwaggerPathProvider() {
    return new ApiRelativeSwaggerPathProvider();
}

private class ApiRelativeSwaggerPathProvider extends
        DefaultSwaggerPathProvider {
    @Override
    public String getAppBasePath() {
        return "/ApiDark/ws";
    }
}

}

SpringBaseWebConfiguration.java :

@Configuration
@ComponentScan(basePackages = {"com.sa.rnd.dark.resources",
        "com.mangofactory.swagger.configuration",
        "com.mangofactory.swagger.controllers"})

@EnableWebMvc
public class SpringBaseWebConfiguration extends WebMvcConfigurerAdapter {
    private List<HttpMessageConverter<?>> messageConverters;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/api-docs").setViewName("redirect:index.html");
    }

    /**
     * The message converters for the content types we support.
     *
     * @return the message converters; returns the same list on subsequent calls
     */
    private List<HttpMessageConverter<?>> getMessageConverters() {
        if (messageConverters == null) {
            messageConverters = new ArrayList<>();

            final MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
            final ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    false);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                    false);
            mappingJacksonHttpMessageConverter.setObjectMapper(mapper);
            messageConverters.add(mappingJacksonHttpMessageConverter);
        }
        return messageConverters;
    }

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        converters.addAll(getMessageConverters());
    }

    @Bean
    public static PropertyPlaceholderConfigurer swaggerProperties() {
        final PropertyPlaceholderConfigurer swaggerProperties = new PropertyPlaceholderConfigurer();
        swaggerProperties.setLocation(new ClassPathResource(
                "swagger.properties"));
        return swaggerProperties;
    }
}

Here are my 3 files to add swagger to my project, atm I just decide to check just 1 method which is :

@Api(description = "CRUD services for containers working with WebDark",
        value = "CRUD Services Containers")
@RestController
@RequestMapping(value = "/container", produces = MediaType.APPLICATION_JSON_VALUE)
public class ContainersResources {
    /**
     * Find all children of a container.
     *
     * @param containerId
     *            ID of the parent container
     * @return ApiResponse
     */


    @ApiOperation(response = ApiResponse.class,
            value = "Find all children containers of one container",
            notes = "Find all children containers of one container")
    @RequestMapping(method = RequestMethod.GET, value = "/{containerId}")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody ApiResponse<List<ContainerModel>> getContainerChildren(
            @ApiParam(required = true, value = "The id of the container parent",
                    name = "containerId")@PathVariable("containerId") final String containerId) {
        ApiResponse<List<ContainerModel>> result = new ApiResponse<>();
        result.setMessage("getContainerChildren  method of new Api Dark");
        result.setSuccess(true);
        result.setTotal(9000);
        return result;
    }
}

My results : I can access the following url http://localhost:8080/ApiDark/ws/api-docs but I get the json value like :

{"apiVersion":"1","swaggerVersion":"1.2","authorizations":{"basicAuth":{"type":"basicAuth"}},"info":{"title":"Swagger Spring MVC for Dark Api","description":"Sample application demonstrating how to use swagger-springmvc in a no-XML environment.","termsOfServiceUrl":"http://en.wikipedia.org/wiki/Terms_of_service","contact":"michael@laccetti.com","license":"Apache 2.0","licenseUrl":"http://www.apache.org/licenses/LICENSE-2.0.html"}}

That's why I decided to add swagger-ui. I add the content of dist folder (taken from swagger-ui) to my src/main/webapp folder. And modify the content of index.html to point to my url :

<script type="text/javascript">
$(function () {
  window.swaggerUi = new SwaggerUi({
      url: "http://localhost:8080/ApiDark/ws/api-docs.json",
  dom_id: "swagger-ui-container",

But I can't access to swagger-ui interface, I just have the json result... Need help to make it work please !


Source: (StackOverflow)

Make model-schema capture element addition on an array field request

I am doing an adapter for a REST API. I've used model schema for the POST and PUT method's body. @RequestBody Model1 requestBody at the adapter.

Now, I encountered body with fields that requires an array.

Swagger UI body input

Time 1 ) On Swagger load, Model-initiated :

{
    "field1"         : "",
    "field2Optional" : "",
    "fieldArray"     : [
        { "field2a"                  :  "input2a" }
    ]

}

Time 2 ) User-edited :

{
    "field1"         : "input1",
    "field2Optional" : "",
    "fieldArray"     : [
        { "field2"        :  "input2a" },
        { "field2"        :  "input2b-userAddition " }
    ]
}

Model1.groovy

@XmlElement
String field1 = ''

@XmlElement
String fieldOptional = ''

@XmlElement
ArrayList<Model2> fieldArray = new ArrayList<>( Arrays.asList(new Model2()) ).get(0)

}

Model2.groovy

@XmlElement
String field2 = ''

I want Model1 to capture/save the elements the user added to the fieldArray like, { "field2" : "input2b-userAddition " }. With the current code, I can only get the first element of the array get(0), I don't want to create many instance of Model2 unless the user said so.

The solution I have in mind is to use @RequestBody Map requestBody inside Model1.groovy to get the whole body request and compare the actual user input vs the model. Then add the fields not found in the model but found in the actual user input. I wonder if there is a better way to do this?


Source: (StackOverflow)

Swagger UI shows error (validation) when deployed

I have the swagger ui embedded in my application. And when I run my node application locally the UI works great.

However when I deploy the UI to my 'real' server I get an error image in the bottom right of my swagger ui:

enter image description here

I am sure this is something I am doing that is screwing it up but I have no idea. Again works locally when I access swagger ui via http.

However when I deploy I run through apache and serve out over https, I see an error. Even worse none of my 'Try it' calls work when deployed. Seems like the request is not being made.

Looks like the UI makes a call to a validator with my swagger.json, however that call works locally.

What am I doing wrong?

When I click the error icon, I get:

enter image description here


Source: (StackOverflow)

How to break swagger 2.0 JSON file into multiple modules

I'm trying to break my API document up into multiple JSON files that can be edited independently. All the examples I've been able to find use the Swagger 1.2 schema which has a "api":{} object for breaking it down. That appears to be missing from the 2.0 schema (http://json.schemastore.org/swagger-2.0). All that defines is a single "paths" array where it bundles all the API endpoints into that single array. The effect of this in the swagger-ui is there is a single "default" category that everything gets bundled into and no way that I can tell to split it up.

TLDR: How do you split operations from paths in the swagger 2.0 schema

{
  "swagger": "2.0",
  "info": {
    "description": "My API",
    "version": "1.0.0",
    "title": "My API",
    "termsOfService": "http://www.domain.com",
    "contact": {
      "name": "support@domain.com"
    }
  },
  "basePath": "/",
  "schemes": [
    "http"
  ],
  "paths": {
    "Authorization/LoginAPI": {
      "post": {
        "summary": "Authenticates you to the system and produces a session token that will be used for future calls",
        "description": "",
        "operationId": "LoginAPI",
        "consumes": [
          "application/x-www-form-urlencoded"
        ],
        "produces": [
          "application/json"
        ],
        "parameters": [{
          "in": "formData",
          "name": "UserName",
          "description": "Login Username",
          "required": true,
          "type": "string"

        }, {
          "in": "formData",
          "name": "Password",
          "description": "Password",
          "required": true,
          "type": "string"

        }],
        "responses": {
          "200": {
            "description": "API Response with session ID if login is allowed",
            "schema": {
              "$ref": "#/definitions/Authorization"
            }
          }
        }
      }
    }
  }
}


Source: (StackOverflow)

how to view my index.html file inside webapp which is cloned from swagger ui on a url

maven-3.0.5

I want to access the swagger sample application on a browser. I'm following the instructions of sample swagger-core using this link(https://github.com/wordnik/swagger-core/tree/master/samples/java-jaxrs).

I have cloned the swagger ui from this link(https://github.com/wordnik/swagger-ui) and placed under the webapp folder.

How can i view my index.html file inside a web-app folder which is cloned from swagger-ui on a url?

Whenever I try to access a url it displays:

This XML file does not appear to have any style information associated with it. The document tree is shown below.

<apiResponse>
  <message>  
     null for url: http://<host>:8002/api/api-docs
  </message>
  <type>
     unknown
  </type>
</apiResponse>

I can't access the swagger-ui. Please help me to do that.


Source: (StackOverflow)

How can I describe complex json model in swagger

I'm trying to use Swagger to describe web-api I'm building. The problem is that I can't understand how to describe complex json object?

For example, how to describe this objects:

{
  name: "Jhon",
  address: [
    {
      type: "home",
      line1: "1st street"
    },
    {
       type: "office",
       line1: "2nd street"
    }
  ]
}

Source: (StackOverflow)

best way to tell swaggerui where the host is

When I build my swagger.json file I do not know which host to use. However I can work it out when my page that hosts swaggerui loads (in fact I might want to offer the user a choice). I hoped to see an options.host on the config for the swaggerUI object - I dont see one. Is there an existing way of doing this that I cant find or do I simply have to hack my way through the code and add this capability (pointers to the best place to do it would be welcome)


Source: (StackOverflow)

How to document OData endpoints (swagger, swashbuckle, other)?

What is the best way of documenting OData endpoints? Is there a way to use Swashbuckle for it?


Source: (StackOverflow)

Default model example in Swashbuckle (Swagger)

I'm running ASP WebAPI 2 and successfully installed Swashbuckle. I am trying to figure out how one defines what the default schema values are?

For example, on the Swagger live demo site they changed the default value of pet to "doggie". They also defined the allowable values for status. (Live Demo)

Example 1 Example 2


Source: (StackOverflow)