Can't open OpenApi (Swagger) page - java

Gradle:
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.13'
implementation group: 'io.swagger.core.v3', name: 'swagger-annotations', version: '2.2.7'
Properties:
springdoc.swagger-ui.enabled=true
springdoc.swagger-ui.path=/swagger-ui.html
Controller:
#RestController
#RequestMapping("/api/v1/cheque")
#FieldDefaults(level = AccessLevel.PRIVATE,makeFinal = true)
public class ChequeController {
ProductService productService;
public ChequeController(ProductService productService) {
this.productService = productService;
}
#GetMapping(value = "/get/{id}", produces = "application/json")
public Optional<Product> getByid(#PathVariable Long id) {
return productService.getById(id);
}
#GetMapping("/test")
public String test() {
return "test";
}
}
Conf:
#Configuration
public class OpenApiConfiguration {
#Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(
new Info()
.title("Example Swagger Api")
.version("1.0.0")
);
}
}
Trying to open in localhost:8080/swagger-ui.html and getting:
Whitelabel Error Page There was an unexpected error (type=Not Found, status=404). in https://springdoc.org/#getting-started saying, that it will automatically deploy swagger-ui to a spring-boot application
what im doing wrong

For swagger v3+, the swagger ui default access is now swagger-ui/ instead of swagger-ui.html
You should be able to access by amending your url to localhost:8080/swagger-ui/

Related

Spring boot 3 + Swagger not working with updated version

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();
}
}

Springdoc OpenAPI 3.0 Swagger - GroupedOpenApi not working in Spring MVC

I'm using springdoc-openapi-ui 1.6.14
I have following class
#Configuration
public class GroupsConfig {
private final PropertyResolver propertyResolver;
public GroupsConfig(PropertyResolver propertyResolver) {
this.propertyResolver = propertyResolver;
}
#Bean
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.group("admin")
.pathsToMatch("/admin/**")
.build();
}
#Bean
public GroupedOpenApi externalApi() {
return GroupedOpenApi.builder()
.group("external")
.pathsToMatch("/external/**")
.build();
}
#Bean
public GroupedOpenApi clientApi() {
return GroupedOpenApi.builder()
.group("client")
.pathsToMatch("/client/**")
.build();
}
#Bean
public GroupedOpenApi externalClientApi() {
return GroupedOpenApi.builder()
.group("extclient")
.pathsToMatch("/extclient/**")
.build();
}
#Bean
public OpenAPI apiInfo() {
String title = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_TITLE);
String description = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_DESCRIPTION);
String version = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_VERSION);
String contactName = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_CONTACT_NAME);
String contactUrl = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_CONTACT_URL);
String contactEmail = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_CONTACT_EMAIL);
String termsOfServiceUrl = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_TERMS_OF_SERVICE_URL);
String licence = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_LICENCE);
String licenceUrl = propertyResolver.getRequiredProperty(SwaggerPropertyKey.API_LICENCE_URL);
Contact contact = new Contact()
.name(contactName)
.url(contactUrl)
.email(contactEmail);
return new OpenAPI()
.info(new Info().title(title)
.description(description)
.version(version)
.license(new License().name(licence).url(licenceUrl))
.contact(contact)
.termsOfService(termsOfServiceUrl))
.components(new Components());
}
}
The OpenAPI info is working correctly and displayed in the UI.
I then have follewing class to import all Springdoc configurations manually
#Configuration
#Import({org.springdoc.core.SpringDocConfigProperties.class,
org.springdoc.webmvc.core.MultipleOpenApiSupportConfiguration.class,
org.springdoc.core.SpringDocConfiguration.class, org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class,
SwaggerUiConfigParameters.class, SwaggerUiOAuthProperties.class,
org.springdoc.core.SwaggerUiConfigProperties.class, org.springdoc.core.SwaggerUiOAuthProperties.class,
org.springdoc.webmvc.ui.SwaggerConfig.class, GroupsConfig.class,
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration.class})
public class SwaggerConfig {
}
If I go to /v3/api-docs, I get a giant JSON with all the different paths in my application. If I go to /v3/api-docs/admin, I get a 404. So the GroupedOpenApi beans are not getting picked up by Springdoc.
Anyone having the same issue or an idea how to fix this?
Thanks in advance!
Edit: I just tried it with 1.4.4 and it works. What should I do to get it working with the newest version?

Open API 3.0 using openapi-generator-maven-plugin not showing any swagger doc

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.

Jersey, Tomcat: The requested resource is not available error in InjelliJ

I am new to Jersey and trying to convert a project from Spring MVC into Jersey. With my current build however, all requests return a resource not available error. Any help would be greatly appreciated.
My Dependencies:
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.boot:spring-boot-starter-data-jpa:1.4.0.RELEASE")
compile("org.springframework.boot:spring-boot-starter-jersey")
runtime('org.hsqldb:hsqldb')
compileOnly("org.springframework.boot:spring-boot-starter-tomcat")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
My Jersey Config
#Configuration
public class JersyConfig extends ResourceConfig {
public JersyConfig() {
registerEndpoints();
configureSwagger();
}
private void configureSwagger() {
register(ApiListingResource.class);
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.0");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8090");
beanConfig.setBasePath("/");
beanConfig.setResourcePackage(OwnerController.class.getPackage().getName());
beanConfig.setPrettyPrint(true);
beanConfig.setScan(true);
}
private void registerEndpoints() {
register(OwnerController.class);
}
}
#Api(value = "Owner controller", tags = {"Owner resource"})
public class OwnerController {
private final ClinicService clinicService;
#Autowired
public OwnerController(ClinicService clinicService) {
this.clinicService = clinicService;
}
#GET
#Path("/{ownerId}")
#Produces(MediaType.APPLICATION_JSON)
#ApiOperation(value = "get owner by id", response = Owner.class)
public Response getOwner(
#ApiParam(name = "owner id", value = "owner id that must be fetched") #PathParam("ownerId") int id ) {
Owner owner = clinicService.findOwnerById(id);
return Response.status(200).entity(owner).build();
}
#GET
#Path("/owners")
#Produces(MediaType.APPLICATION_JSON)
#ApiOperation(value = "get all owners", response = Owner.class, responseContainer = "List")
public Response getOwners() {
List<Owner> owner = (List<Owner>) clinicService.findAllOwners();
return Response.status(200).entity(owner).build();
}
}
Register your package which contains jersey resources using packages() method in JerseryConfig() constructor -
public JersyConfig() {
packages("PACKAGE_CONTAINING_JERSEY_RESOURCES");
registerEndpoints();
configureSwagger();
}

Getting a 404 when trying to load index.jsp using Spring MVC

Even after checking other answers and comparing the code with other applications that I have developed, I can't get to load index.jsp properly. I'm working with Spring MVC, using annotations. The thing is that I have done the same before and it has worked, what could my error be this time?
MvcConfig:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "tool.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {
private static final String VIEW_CONTROLLER = "/index.htm";
private static final String VIEW_NAME = "/view/index.jsp";
#Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController(VIEW_CONTROLLER).setViewName(VIEW_NAME);
}
#Override
public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebInitializer:
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(final ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(BasicConfig.class, MvcConfig.class);
servletContext.addListener(new ContextLoaderListener(context));
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
ServletRegistration.Dynamic dispatcher;
dispatcher = servletContext.addServlet("dispatcher",
new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
IndexController:
#Controller
public class IndexController {
private static final String INDEX_VIEW = "/view/index.jsp";
#RequestMapping(value = { "/", "/index" })
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView(INDEX_VIEW);
return modelAndView;
}
}
Folder Structure:
Folder Structure
Console messages from Tomcat initiallization that could be relevant:
Console messages
Any help will be appreciated, thanks!
EDIT: build.gradle
apply plugin: 'base'
apply plugin:'war'
apply plugin: 'jetty'
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin:'idea'
ext.springVersion='4.1.4.RELEASE'
ext.hibernateVersion='4.3.8.Final'
ext.hibernateValidatorVersion='5.1.3.Final'
repositories {
mavenCentral()
}
dependencies {
compile 'org.slf4j:slf4j-api:1.7.10'
compile 'org.slf4j:slf4j-simple:1.7.10'
compile 'ch.qos.logback:logback-core:1.1.2'
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
compile 'org.springframework.data:spring-data-jpa:1.3.0.RELEASE'
compile "org.springframework:spring-jdbc:$springVersion"
compile "org.springframework:spring-tx:$springVersion"
compile "org.springframework:spring-orm:$springVersion"
compile "org.springframework:spring-aop:$springVersion"
compile "org.springframework:spring-webmvc:$springVersion"
compile "org.springframework:spring-oxm:$springVersion"
compile "org.springframework.security:spring-security-core:4.1.3.RELEASE"
compile "org.hibernate:hibernate-entitymanager:$hibernateVersion"
compile "org.hibernate:hibernate-core:$hibernateVersion"
compile "org.hibernate:hibernate-validator:$hibernateValidatorVersion"
compile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final"
compile 'org.postgresql:postgresql:9.4-1201-jdbc41'
compile 'javax.servlet.jsp:javax.servlet.jsp-api:2.3.1'
compile 'javax.servlet:jstl:1.2'
testCompile "org.mockito:mockito-core:1.+"
testCompile 'junit:junit:4.11'
}
eclipse {
project.natures "org.springframework.ide.eclipse.core.springnature"
}
Also try to modify your controller class according to spring's good practices.
#Controller
public class IndexController {
//private static final String INDEX_VIEW = "/view/index.jsp";
#RequestMapping(value = { "/", "/index" })
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView("index");
return modelAndView;
}
}
I have apparently found what was the problem. First of all, I'm working on Eclipse IDE. The solution that I came to was adding the folder "webapp" to the "Web Deployment Assembly" in the project's properties. After doing this, the index.jsp is loading properly and I'm not getting a 404 error anymore.

Categories