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.
Related
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();
}
}
I have an existing REST API built using Spring Boot. On one of my functions on the service layer, I need to call an external REST service that is protected by OAuth2 (client-credentials).
Using Spring Boot 2.3, I realized OAuth2RestTemplate is deprecated, so I went with using WebClient.
Following this tutorial - https://www.baeldung.com/spring-webclient-oauth2, I now have my WebClientConfig class as follows:
#Configuration
class WebClientConfig {
#Bean
fun webClient(
clientRegistrations: ClientRegistrationRepository?,
authorizedClients: OAuth2AuthorizedClientRepository?): WebClient? {
val oauth2 = ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients)
oauth2.setDefaultOAuth2AuthorizedClient(false)
oauth2.setDefaultClientRegistrationId("test")
return WebClient.builder()
.apply(oauth2.oauth2Configuration())
.build()
}
}
And in my properties file, I have:
spring:
security:
oauth2:
client:
registration:
test:
client-id: <redacted>
client-secret: <redacted>
authorization-grant-type: client_credentials
provider:
test:
token-uri: <redacted>
I can't even tell if this is working or not, because I keep getting the following error when accessing a different endpoint on my API that has nothing to do with this OAuth2 authentication:
java.lang.IllegalArgumentException: Invalid Authorization Grant Type (client_credentials) for Client Registration with Id: test
I'm at my wits end because I can't overcome this issue... any help would be very appreciated! Thanks!
This is working for me:
#Bean
public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
authorizedClientManager);
oauth2Client.setDefaultClientRegistrationId("test");
return WebClient.builder()
.apply(oauth2Client.oauth2Configuration())
.build();
}
#Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.refreshToken()
.clientCredentials()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}
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.
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
I learn create Web Service soap from guide Producing a SOAP web service
When I have jar file and run main method everything is ok. I change to war file run by mvn spring-boot:run is the same.
But next i have a problem and I wont resolve it without use xml configuration (if I can) only annotation or java code
I found many similar issue but none was help
e.g
https://stackoverflow.com/questions/21115205/spring-boot-with-spring-ws-soap-endpoint-not-accessable
http://stackoverflow.com/questions/26873168/spring-boot-webservice-from-wsdl-not-working
Deploy war on wildFly 8.2 after that show wsdl but nothing else.
I change
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
to
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(WebServiceConfig.class);
}
}
and deploy in wildFly 8.2 after that show wsdl but when put request in SoapUI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:gs="http://spring.io/guides/gs-producing-web-service">
<soapenv:Header/>
<soapenv:Body>
<gs:getCountryRequest>
<gs:name>Spain</gs:name>
</gs:getCountryRequest>
</soapenv:Body>
</soapenv:Envelope>
get
WARN [org.springframework.ws.server.EndpointNotFound] (default task-7) No endpoint mapping found `for [SaajSoapMessage {http://spring.io/guides/gs-producing-web-service}getCountryRequest]`
and clear page in soapUI
I search similar issue e.g Endpoint not accessable
changed
#Bean
public ServletRegistrationBean dispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
to
#Bean
public MessageDispatcherServlet dispatcherServlet() {
return new MessageDispatcherServlet();
}
is the same, but when I use
#Bean
public MessageDispatcherServlet dispatcherServlet() {
return new MessageDispatcherServlet(getContext());
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new
AnnotationConfigWebApplicationContext();
context.setConfigLocation(Application.class.getName());
return context;
}
get
Caused by: java.lang.NoSuchMethodError: org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.applicationContext(Lorg/springframework/context/ApplicationContext;)Lorg/springframework/http/converter/json/Jackson2ObjectMapperBuilder;
whole error log and whole eclipse project
Thanks M. Deinum for reply it's really helpful.
First I tried use only Application class but I couldn't run server. Error in log Caused by: java.lang.ClassNotFoundException: org.xnio.SslClientAuthMode next I found solution with create two classes WebServiceConfig and Application.After changing server started , wsdl showed for me it was good change, therefore thank you again.
This issue is caused spring-boot bug GitHub, now I moving whole code from WebServiceConfig to Application and using the newest compile spring-boot. After that WS work good.In pom Paste current Application class maybe someone will have the same problem.
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean
public ServletRegistrationBean dispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(
XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws/");
wsdl11Definition
.setTargetNamespace("http://spring.io/guides/gs-producing-web-service");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
private WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(Application.class.getName());
return context;
}
}