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();
}
}
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();
}
}
Facing this issue with Open API 3.0, I am generating the code using openapi-generator-maven-plugin. I am able to generate the code as well. Code is there in the finally generated Jar of Spring boot as well. But Some how I am not able to see the swagger-doc. All I see is this pop-up with this description
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/. Please enter the location manually:
I tried setting up the baseUrl property, like this
baseUrl=http://localhost:8080/api
This isn't working, generated Config & controller has following code.
#Controller
public class HomeController {
#RequestMapping("/")
public String index() {
return "redirect:swagger-ui.html";
}
}
Following is configuration class.
#Configuration
#EnableSwagger2
public class OpenAPIDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("School REST API")
.description("School REST API")
.license("ABC")
.licenseUrl("http://localhost:8080")
.termsOfServiceUrl("")
.version("1.0.0")
.contact(new Contact("","", "xyz#abc.com"))
.build();
}
#Bean
public Docket customImplementation(ServletContext servletContext, #Value("${openapi.schoolRest.base-path:}") String basePath) {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.school.rest.generated.controllers"))
.build()
.pathProvider(new BasePathAwareRelativePathProvider(servletContext, basePath))
.directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class)
.genericModelSubstitutes(Optional.class)
.apiInfo(apiInfo());
}
class BasePathAwareRelativePathProvider extends RelativePathProvider {
private String basePath;
public BasePathAwareRelativePathProvider(ServletContext servletContext, String basePath) {
super(servletContext);
this.basePath = basePath;
}
#Override
protected String applicationPath() {
return Paths.removeAdjacentForwardSlashes(UriComponentsBuilder.fromPath(super.applicationPath()).path(basePath).build().toString());
}
#Override
public String getOperationPath(String operationPath) {
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
return Paths.removeAdjacentForwardSlashes(
uriComponentsBuilder.path(operationPath.replaceFirst("^" + basePath, "")).build().toString());
}
}
}
I have also removed the springfox & swagger related jars from my project.
Please advice.
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");
}
}
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