I used swagger 2.9.2 in my spring boot app.
localhost:8080/api-docs works fine.
However, localhost:8080/swagger-ui.html returns writelabel error.
localhost:8080/v2/swagger-ui.html and localhost:8080/api/swagger-ui.html return the same error.
I must have missed something simple. Thanks.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Aug 22 10:05:48 CDT 2018
There was an unexpected error (type=Not Found, status=404).
No message available
In build.gradle, I have dependency of springfox.
compile("io.springfox:springfox-swagger2:2.9.2")
compile("io.springfox:springfox-swagger-ui:2.9.2")
swaggerconfig.java
#Configuration
#EnableSwagger2
public class SwaggerConfig{
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage(MyServiceController.class.getPackage().getName()))
//.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.ant("/api/**"))
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
String description = "Company - My API";
return new ApiInfoBuilder()
.title("REST API")
.description(description)
.version("1.0")
.build();
}
MyServiceController.java
#ApiOperation(value = "some description",
response = MyServiceResponse.class)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "ok"),
#ApiResponse(code = 400, message = "Bad Request"),
#ApiResponse(code = 401, message = "not authorized"),
#ApiResponse(code = 403, message = "not authenticated"),
#ApiResponse(code = 404, message = "The resource you were trying to reach is not found"),
#ApiResponse(code=500, message = "Interval Server Error")
})
#RequestMapping(method = RequestMethod.POST, value = "/api/component/operation", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
#ResponseBody
{
do something
}
Hey I am using Spring boot 2.1.4, Swagger 2.9.2, I faced the same issue and got resolved by the following:
It seems that you have the required dependencies so this is not the issue.
I think the issue that you have to implement WebMvcConfigure and override addResourceHandlers method:
#Configuration
#EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
// your Docket and ApiInfo methods
#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/");
}
Just try to add it and Share what happen with you.
Return the Docket bean like below :
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
and add #RestController annotation above your controller class
So if u have correctly written the swaggerConfig code also added the right dependencies and still getting error
The ultimate solution is
You need to have perfect combination of swagger version and spring boot version
Just change the spring boot and swagger version as below
Check in your pom.xml or gradle build
Spring boot version :- <version>1.4.1.RELEASE</version>
Swagger and Sawgger ur version:- <version>2.2.2</version>
There are other combinations available but that u need to try on trial basis
I have the same problem, and solve with this Docket bean config:
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build()
.apiInfo(this.apiInfo());
}
it works for me.
I faced the same issue and got resolved by the following
You can use one dependency:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
SwaggerConfig class like below :
#Configuration
#EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
#Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2);
}
#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/");
}
}
do not use #EnableSwagger2 3.0 version
http://localhost:8080/swagger-ui/index.html
Related
Trying to generate swagger UI but not able to generate using spring boot 3.0.2 and java 17.0.2. Below is my details
Gradle dependency
implementation "io.springfox:springfox-boot-starter:3.0.0"
Swagger Configuration
#SpringBootApplication
#ComponentScan({"com.bl.*"})
#EnableJpaRepositories(basePackages = { "com.bl.entity.repository" })
#EntityScan({"com.bl.entity"})
public class BlApiUiApplication {
public static void main(String[] args) {
SpringApplication.run(BlApiUiApplication.class, args);
}
#Bean
Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("UI Details")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API")
.description("UI")
.licenseUrl("URL").version("1.0").build();
}
}
Controller
#RestController
#RequestMapping("/v0")
#Api(value = "API")
public class UIController {
private final Logger logger = LoggerFactory.getLogger(UIController.class);
#ApiOperation(value = "isRunning", notes = "To check whether service is running or not")
#GetMapping(value = "/isRunning", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> test() {
return new ResponseEntity<>("Service is running.", HttpStatus.OK);
}
#ApiOperation(value = "/user/login", notes = "To login user")
#ApiResponses(value = { #ApiResponse(code = 200, message = "Successful"),
#ApiResponse(code = 500, message = "Internal server error"),
#ApiResponse(code = 1001, message = "Application specific error.") })
#PostMapping(value = "/user/login", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<BaseGatewayResponse> login(#RequestBody final UserLoginRequest requestDTO) {
logger.info("Login request: {}", requestDTO);
UserLoginResponse responseDTO = userGatewayService.login(requestDTO);
logger.info("Exit Login response: {} for request: {}", responseDTO, requestDTO);
return new ResponseEntity<>(responseDTO, HttpStatus.OK);
}
After running its not working getting below error.
Swagger URL : http://localhost:8080/BLApiUI/swagger-ui/index.html
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Feb 03 22:59:52 IST 2023
There was an unexpected error (type=Not Found, status=404).
in case you want to try "openapi", simply add annotation "OpenAPIDefinition" to Application class, no other code change is needed.
implementation "org.springdoc:springdoc-openapi-ui:1.6.12"
springboot 2.7.0
java 17
#OpenAPIDefinition
public class MyApplication
Swagger URL : http://localhost:8080/swagger-ui/index.html#/
Recently we have upgraded to Java 17, We have added 'org.springdoc:springdoc-openapi-ui:1.6.12' dependency as no other old swagger related dependency were working and Swagger Configuration class looks simple for us now
#Configuration
public class SwaggerConfiguration{
#Bean
public GroupedOpenApi publicApi(){
GroupedOpenApi.builder().group("springshop-publish").pathsToMatch("/**").build();
}
}
I have a yaml file to generate my endpoints based on the OpenAPI principle, but when I open my swagger-ui I see:
openapi: 3.0.2
info:
....
....
paths:
/cities:
get:
tags:
- Cities
summary: Get all cities
operationId: getAllCities
responses:
200:
description: successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/City'
404:
description: Cities not found
content: {}
and the swagger config look like this:
#Configuration
#EnableSwagger2
public class Swagger2Config {
public static final String REST_PACKAGE = "package";
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage(REST_PACKAGE))
.paths(PathSelectors.any())
.build();
}
}
What I'm missing to remove cities-api-controller from swagger ui ?
public class Swagger2Config {
public static final String REST_PACKAGE = "package";
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage(REST_PACKAGE))
.paths(regex("/*.*"))
.build();
}
}
Please find the config details.
Its a spring application
Dependency
//swagger for api documentation
compile('io.springfox:springfox-swagger2:2.9.2')
compile('io.springfox:springfox-swagger-ui:2.9.2')
Code
#EnableSwagger2
#ComponentScan(basePackages = "com.myntra.catalog.service")
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build().apiInfo(apiEndPointsInfo());
}
private ApiInfo apiEndPointsInfo() {
return new ApiInfoBuilder().title("Spring REST APIs")
.description("Catalog Service APIs")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.version("1.0.0")
.build();
}
}
Getting this log in build
05:35:54.998 INFO springfox.documentation.spring.web.PropertySourcedRequestMappingHandlerMapping [RMI TCP Connection(2)-127.0.0.1] - Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
But
**/v2/api-docs is giving 404 **
Getting the above error. Can someone please help here.
I have been trying to add authorization in requests that I try from swagger-ui, but in the request, the authorization header is always coming as null.
This is what I have done.
private ApiKey apiKey() {
return new ApiKey("apiKey", "Authorization",
"header"); //`apiKey` is the name of the APIKey, `Authorization` is the key in the request header
}
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("com.example.app"))
.paths(PathSelectors.any()).build().apiInfo(apiInfo()).securitySchemes(Arrays.asList(apiKey()));
}
Can anyone please give some pointers? Thanks.
You can try this SwaggerConfig
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any())
.build().securitySchemes(Lists.newArrayList(apiKey()));
}
private ApiKey apiKey() {
return new ApiKey("AUTHORIZATION", "api_key", "header");
}
}
This is a Spring boot application, where as I mentioned in subject "appConfig" root element is missing from the response when I added Swagger. Any Help on this forum will be appreciated.
Here is my response object class:
#JsonRootName(value = "appConfig")
public class AppConfig {
// Using lombok for getter setters
#Getter
#Setter
#JsonProperty("toggles")
private List<Toggle> toggles;
#Getter
#Setter
#JsonProperty("resources")
private List<Resource> resources;
This is my restController
#RequestMapping(value = "/appConfig", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(HttpStatus.OK)
public AppConfig appConfig() {
final AppConfig appConfig =delegate.getAppConfig();
return appConfig;
}
This is what I am getting in the response
//MISSING appConfig root element !!!!
{
"resources": [
{
"lastUpdateTimeStamp": "string",
"resourceName": "string"
}
],
"toggles": [
{
"name": "string",
"state": true
}
]
}
This is my POM dependency for Swagger:
<!-- Swagger dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
<scope>compile</scope>
</dependency>
This is my Swagger Configuration class:
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
#Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
private ApiInfo apiInfo() {
return new ApiInfo(
"Blah",
"Blah",
"Blah",
"Terms of service",
new Contact("Blah Administrator", "URL", "Email"),
"License of API", "API license URL");
}
Work around which is UGLY! is define a Dummy response object and wrap your response inside it. So Swagger strips that off and gives the answer what is expected. Still looking for an answer!
Enable these properties at your ObjectMapper configuration:
jsonObjectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
jsonObjectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
I got same problem, before using swagger i had response CustomResponse class with getter and setters:
public class CustomResponse<T> {
private T data;
private String message;
}
and response looked liked this:
{
"CustomResponse" : {
"data" : {
"prop" : "prop",
"prop 1" : "prop1",
},
"message" : "true",
}
}
after implementing swagger result is like this:
{
"data" : {
"prop" : "prop",
"prop 1" : "prop1",
},
"message" : "true"
}
tried to add #JsonRootName("CustomResponse") but result is same.
here is swagger config:
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.additionalModels(typeResolver.resolve(CustomResponse.class))
.genericModelSubstitutes(CustomResponse.class)
.select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
also tried #amseager solution:
#Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
return mapper;
}
is there any way that to return response with root name.
I was facing the same issues using OpenApi Swagger , I've fixed it by adding a OpenApiCustomiser.
To avoid duplicated answer , I posted the solution Here