Swagger REST API documentation with Spring Boot - java

I want to use Swagger 2.0 with my Spring Boot RESTful web service to generate documentation. I have searched quite a bit for an answer to this. Basically I have a Spring Boot project with a set of controllers and I want to document the API's. I have the following dependencies setup in my POM file.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
This is my Swagger configuration class with the #Configuration and #EnableSwagger2:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("/api/.*"))
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My application title")
.description("This is a test of documenting EST API's")
.version("V1.2")
.termsOfServiceUrl("http://terms-of-services.url")
.license("LICENSE")
.licenseUrl("http://url-to-license.com")
.build();
}
}
From what I have gathered in reading a couple of other answers here that at this point I should be able to see something at a URL such as http://myapp/v2/api-docs or alternatively http://localhost:8080/myapp/api-docs I have made the assumption that the "myapp" portion of the above URL refers to the name of the class in which my main resides (is this correct)? Also I have tried this with port 8080 and port 80 and the bottom line is that I see nothing other than site can't be reached. I have looked at the answers provided here and here however I'm not having any success. Any help would be much appreciated, thank you in advance.

As you can see on the following documentation :
https://springfox.github.io/springfox/docs/snapshot/#springfox-swagger-ui
The endpoint is now on swagger-ui.html, for your case, it will be http://localhost:8080/myapp/swagger-ui.html

I used, <artifactId>springdoc-openapi-ui</artifactId> with
public class OpenApiConfiguration{
#Bean
public GroupedOpenApi abcApp(){
String[] abcAppRootPath={"com.stockoverflow.swagger"};
return GroupedOpenApi.builder().group("my app").packagesToScan(abcAppRootPath).build();
}
}
reference : https://springdoc.org/#getting-started

Related

Springfox-boot-starter swagger Instant handling

I have a problem with swagger documentation using SpringBoot with Springfox-boot-starter.
I use java.time.Instant wrapped in java.util.Optional in my REST API which works fine:
#GetMapping("/{subscriptionId}/{variableAlias}")
public PaginatedResultDTO<MonitoredVariableDTO> getReportedVariables(
#PathVariable String subscriptionId,
#PathVariable String variableAlias,
Optional<Instant> from,
Optional<Instant> to) { ... }
But for some reason, Swagger documentation cannot handle the Optional type correctly and seems to handle it through reflection as EpochSeconds and Nano attributes instead of one field:
I would like to make swagger expect from and to instants in ISO format, just like Spring does and how I use it in Insomnia:
When I tried to remove the Optional wrapper, it seems to work
Is there a way to make this work with the Optional? Thanks for any advice!
Spring boot version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath />
</parent>
Springfox-boot-starter version
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
We had exactly the same problem that you.
We solved it with this SpringFox configuration:
#Configuration
#EnableSwagger2
public class SpringfoxConfiguration {
#Value("${api-doc.version}")
private String apiInfoVersion;
#Autowired
private TypeResolver typeResolver;
#Bean
public Docket customDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("xxx")
//Some other code unrelated to this problem
.alternateTypeRules(
// Rule to correctly process Optional<Instant> variables
// and generate "type: string, format: date-time", as for Instant variables,
// instead of "$ref" : "#/definitions/Instant"
AlternateTypeRules.newRule(
typeResolver.resolve(Optional.class, Instant.class),
typeResolver.resolve(Date.class),
Ordered.HIGHEST_PRECEDENCE
))
.genericModelSubstitutes(Optional.class)
.select()
//Some more code unrelated to this problem
.build();
}
}
With spring fox the problem is it doesn't use the custom ObjectMapper which you have defined as a Bean.
Springfox creates own ObjectMapper using new keyword. Hence, any module you register with your custom ObjectMapper is pointless for SpringFox. However, Springfox provides an interface to register modules with it's own ObjectMapper.
Create a configuration bean like below in your project and it should work.
#Configuration
public class ObjectMapperModuleRegistrar implements JacksonModuleRegistrar {
#Override
public void maybeRegisterModule(ObjectMapper objectMapper) {
objectMapper.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.findAndRegisterModules();
}
}

Swagger does not show / document my RESTful endpoints (JAX-RS, Spring-boot)

I have developed a RESTful web service in Java and Spring boot using Jax-RS and I would like to document it with Swagger. I have so far successfully managed to map the swagger-ui.html page on http:8080/localhost/<context>/swagger-ui.html. Unfortunately, my RESTful endpoints do not appear anywhere.
What I am using:
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Swagger configuration class
#Configuration
#EnableSwagger2
public class SwaggerConfiguration
{
#Autowired
private TypeResolver typeResolver;
#Bean
public Docket api()
{
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.nick.java.webservice.services"))
.paths(PathSelectors.any())
.build()
.enable(true)
.apiInfo(getApiInfo())
.tags(
new Tag("My web service", "Methods for my RESTful service")
);
}
private ApiInfo getApiInfo() {
ApiInfo apiInfo = new ApiInfoBuilder()
.title("API Documentation")
.description("API")
.version("1.0")
.contact(new Contact("mycompany", "", "nickath#mycompany.com"))
.build();
return apiInfo;
}
an example of the JAX-RS endpoints
package org.nick.java.webservice.services;
#Path("/contextsapi")
#Consumes("application/json")
#Produces("application/json")
#Api(value = "Contexts API", produces = "application/json")
public interface ContextAPI {
#Path("/contexts/contexts")
#GET
#ApiOperation( value = "get contexts",
response = List.class)
List<Context> getContexts();
screenshot of the swagger-ui.html page
as you can see, no 'get contexts' method has been generated
Any idea what I am doing wrong?
======= UPDATE - SERVICE IMPLEMENTATION ========
package org.nick.java.webservice.services.impl;
#Service
#Api(value = "Contexts Api Impl", produces = "application/json", description = "desc")
#Path("/contextsapi")
public class ContextAPIImpl implements ContextAPI {
#Override
#GET
#ApiOperation( value = "get contexts", response = List.class)
public List<Context> getContexts(){
//code ommitted
}
}
Solved
Finally I managed to solve my problem using the Swagger2Feature following the example from here https://code.massoudafrashteh.com/spring-boot-cxf-jaxrs-hibernate-maven-swagger-ui/
Maven dependencies
<cxf.version>3.1.15</cxf.version>
<swagger-ui.version>3.9.2</swagger-ui.version>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description-swagger</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>${swagger-ui.version}</version>
</dependency>
CxfConfig.java
#Configuration
public class CxfConfig {
#Autowired
private Bus bus;
#Bean
public Server rxServer(){
final JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setProvider(new JacksonJsonProvider());
endpoint.setBus(bus);
endpoint.setAddress("/swagger");
endpoint.setServiceBeans(Arrays.<Object>asList(contextAPI());
Swagger2Feature swagger2Feature = new Swagger2Feature();
endpoint.setFeatures(Arrays.asList(swagger2Feature));
return endpoint.create();
}
#Bean
public ContextAPI contextAPI(){
return new ContextAPIImpl();
}
Now the swagger documentation is available on http://localhost:8080///swagger/api-docs?url=//swagger/swagger.json
To customize the endpoint's UI check the manual here
Swagger suppose not to show documentation for any API client. It will generate documentation for your service if there is any with swagger annotations.
To be confirmed about this, try creating a Spring #service and annotate with swagger annotations. The doc will be generated if every other aspects are taken care of. Since you can see the UI, I would assume the dependencies are right.
The idea here is, your task is to document your service and swagger helps with that. It's not your responsibility to generate/publish documentation for API(s) that your service consumes. Since you don't maintain the service, it doesn't make sense to maintain the documentation as well.
When I used Rest client for the first time, I also got a bit perplexed about this. But if you really think about it, this is expected and makes sense.
I would suggest to use Swagger 2 i faced the same issue.
the issue is with the Docket you have implemented , correct regular expression can help.
Example :
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
You can refer to the link above Setting up Swagger 2 Example
The Source code example is also from the above link.

Spring Boot 2.1 cache actuator not present

I have setup a simple spring boot application based on version 2.1 (https://github.com/dkellenb/spring-boot-2.1-cache-actuator-missing). I cannot find the reason why the cache actuator is not available at http://localhost:8080/actuator/caches .
#EnableCaching
#SpringBootApplication
#Controller
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Cacheable(cacheNames = "helloWorld")
#GetMapping
public ResponseEntity<String> hello() {
return ResponseEntity.ok("hello world");
}
}
And for the pom.xml i have added cache and actuator:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Also i have tested with
endpoints.caches.enabled=true
management.endpoints.web.exposure.include=info,health,cache
Note that Cache Actuator is available with JMX, but on on web.
The reason was:
cache is not exposed by default (see https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-endpoints-exposing-endpoints)
There was a typo for the exposure, it should be caches (plural)
I had a similar problem and it turned out that the actuator must be be in the version spring-boot-autoconfigure-2.1.3.RELEASE.jar.
My previous version was spring-boot-actuator-autoconfigure-2.0.2.RELEASE.jar. In this version CachesEndpointAutoConfiguration not exist. This class is responsible for creating the "cachesEndpoint" bean if the "cacheManager" bean is present in the application.
Try the version 2.1.3.

No mapping found for HTTP request with URI [/WEB-INF/views/welcome.jsp] in DispatcherServlet with name 'dispatcherServlet' [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I configured the Application and code the "DispatcherServlet" to viewResolver like this:
#Configuration
#EnableWebMvc
#ComponentScan ({"controllers"})
#EnableAutoConfiguration
#SpringBootApplication
public class Application {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
Controller class to handle requests looks this:
#Controller
public class HelloControllerImpl {
#RequestMapping(value= "/welcome", method= RequestMethod.GET)
public String getWelcomePage(ModelMap model) {
model.addAttribute("message", "Spring 3 MVC - Hello World");
model.addAttribute("name", "vzateychuk");
return "welcome";
}
}
The view file: \WEB-INF\views\welcome.jsp
<html>
<body>
<h1>Hello, : ${name}</h1>
<h2>Message : ${message}</h2>
</body>
</html>
The application structure:
Welcome application structure
I think that something is missing in the configuration files, but I can not see. Could you guest what is wrong and what means: "No mapping found for HTTP request with URI [/WEB-INF/views/welcome.jsp]"?
Should I provide xml configuratin like dispatcher-servlet.xml or something like that?
Thank you in advance.
Update: I guessing that my DispatcherServlet unable to find the appropriate view. I have tryed to completely delete /WEB-INF directory, but nothing changes. Probably something wrong with this code:
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
**viewResolver.setPrefix("/WEB-INF/views/");**
....
Can anybody guess what can be wrong? (May it be if the anotation #EnableAutoConfiguration not allow to define viewResolver's prefix?
I did simple project similiar to yours. You can check on my github
What you have to do is:
Rename hello.html to hello.jsp
Check that you have all dependencies in your pom.xml. I didn't see it so I am not sure if it is wrong. Make sure you have these two dependencies:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
For that point you will find the explanation here
Indeed, you may have a problem with launching it with IDEA Community Version. I have experienced that problem as well. What you can do is first check it using command line and maven. Execute following command:
mvn spring-boot:run
You may also configure your IDEA to run that command. Go to Run->Edit Configuration, click green plus sign on the left side and choose Maven. Then in the "Command line" field write "spring-boot:run", press ok.
And run this configuration.
(Optional) You also have some redundant annotations on your Application class. You can remove:
#Configuration, because #SpringBootApplication already has it
#EnableWebMvc, because Spring Boot adds it automatically when it sees spring-webmvc on the classpath
#EnableAutoConfiguration, because #SpringBootApplication already has it
Note that you need #ComponentScan ({"controllers"}), because of your package structure - you have Application class in different package than your controller.
configure resolver configuration application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring boot will automatically configure your internal view resolver.
and you need to add jstl jars in pom
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
or
to get your view resolver to work add
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
spring-boot has a sample for you

No mapping found for swagger-resources/configuration/ui [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to configure swagger ui in non spring boot app. I have done following things.
1. Added Following dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.5</version>
</dependency>
2. Added Swagger Config class
#Configuration
#EnableSwagger2
#EnableWebMvc
//#PropertySource("classpath:/swagger.properties")
public class SwaggerConfig {
#Bean
public Docket proposalApis(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test")
.select()
.apis(RequestHandlerSelectors.basePackage("com.test.abc"))
.paths(PathSelectors.regex("/test1.*"))
.build()
.apiInfo(testApiInfo());
}
private ApiInfo testApiInfo() {
ApiInfo apiInfo = new ApiInfoBuilder().title("Test APIs").description("GET POST PUT methods are supported ").version("V1").build();
return apiInfo;
}
}
Added following mappings :
<mvc:resources mapping="swagger-ui.html" location="classpath:/META- INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META- INF/resources/webjars/"/>
I am able to access following url's
/v2/api-docs
/swagger-resources
But While loading swagger-ui.html UI gets loaded and on server getting following error
No mapping found for /context/swagger-resources/configuration/ui in Dispatcher servlet
Can someone help?
I'm using Swagger version 2.3.1 in my pom. I wonder why you have different versions for springfox-swagger2 and springfox-swagger-ui artifacts?
My SwaggerConfig class looks like this. No properties:
#EnableSwagger2
#Configuration
public class SwaggerConfig {
#Autowired
private TypeResolver typeResolver;
#Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("FooBar")
.select()
//Ignores controllers annotated with #CustomIgnore
.apis(any()) //Selection by RequestHandler
.paths(paths()) // and by paths
.build()
.apiInfo(apiInfo()
);
}
private ApiInfo apiInfo() {
return new ApiInfo("FooBar",
"A java server based on SpringBoot",
"1.0.0",
null,
"author","","");
}
//Here is an example where we select any api that matches one of these paths
private Predicate<String> paths() {
return or(
regex("/foobar/*.*")
);
}
}
No configuration or resources for me.
The page comes right up when I hit the URL http://localhost:8080/foobar/swagger-ui.html
Different versioning of springfox-swagger2 and springfox-swagger-ui has been an issue. In some cases, like former of 2.5.0 and latter of 2.6.1 version, the integration works fine. But, if former is of 2.6.1 and latter is of 2.4.0, then the ui becomes incompatible. Hence, I suggest if both the dependencies are taken of same version by practice, then unexpected functioning of swagger can be reduced.

Categories