Swagger Ui hangs for api endpoint in spring boot - spring-boot

My client api endpoint is not loading in swagger UI as shown in the image what I need to do? It always show loading icon when I click on any client controller api like get,post
Please post answer Thank You
see picture
SwaggerConfig.groovy
#Configuration
#EnableSwagger2
class SwaggerConfig {
#Bean
Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any()
.paths(PathSelectors.any())
.build().apiInfo(metaData())
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Swagger Example")
.description("\"Swagger configuration for application \"")
.version("1.1.0")
.license("Apache 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.build()
}
}
ClientController.groovy
#RestController
#RequestMapping('/client')
class ClientController {
#Autowired
ClientService clientService
#GetMapping('/')
ResponseEntity<List<Client>> getAllClients() {
List<Client> clients = clientService.getAllClients()
return new ResponseEntity<>(clients, HttpStatus.OK)
}
#GetMapping('/{clientId}')
ResponseEntity<Client> getClientById(#PathVariable("clientId") Integer clientId) {
return new ResponseEntity<>(clientService.getClientById(clientId), HttpStatus.OK)
}
#PostMapping('/create')
ResponseEntity<Client> createClient(#RequestBody Client client) {
return new ResponseEntity<>(clientService.addClient(client), HttpStatus.CREATED)
}
#PutMapping('/update/{clientId}')
ResponseEntity<Client> updateClient(#PathVariable("clientId") Integer clientId, #RequestBody Client client) {
clientService.updateClient(client, clientId)
return new ResponseEntity<>(clientService.getClientById(clientId), HttpStatus.OK)
}
#DeleteMapping('/delete/{clientId}')
ResponseEntity<Client> deleteClient(#PathVariable("clientId") Integer clientId) {
clientService.deleteClientById(clientId)
return new ResponseEntity<>(HttpStatus.NO_CONTENT)
}
}

Related

Add context path to requests in swagger

I have an eureka service which has a swagger. The eureka is on http://localhost:8050
and the service goes by name /service. The issue is that when i open swagger and try to make a request, it sends it to http://localhost:8050/service/somecontroller. The service has a context path "path" so it should be http://localhost:8050/service/path/somecontroller. This is the configuration of the swagger:
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.test")).paths(PathSelectors.any())
.build();
}
Springfox has an open issue (#2817) for your case, you can try one of the workarounds proposed by some users there.
Managed to change the context path of the swagger like this:
#Value("${contextPath}")
private String contextPath;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
//.host(retrieveHostHostname())
.pathProvider(new PathProvider() {
#Override
public String getApplicationBasePath() {
return contextPath;
}
#Override
public String getOperationPath(String s) {
return s.replace("somecontroller", contextPath+"/somecontroller");
}
#Override
public String getResourceListingPath(String s, String s1) {
return "/";
}
}).select()
.apis(RequestHandlerSelectors.basePackage("com.test")).paths(PathSelectors.any())
.build();
}

How to pattern match of a API while exposing to Swagger2 in Spring Boot?

Below is the controller for which I need to write swagger2 API documents:
#RestController
#RequestMapping("/abc/def/pqr")
public class Controller {
#GetMapping(path = "", consumes = "application/json", produces = "application/json")
#ResponseBody
public <T> PagedResources<SomeResource> get(Pageable pageable,
Assembler assembler) {
Page<Something> somethings = service.get(pageable);
return pagedAssembler.toResource(somethings, assembler);
}
}
Below is the code for through which I am trying to write swagger to API documentations:
#Bean
public Docket swaggerConfiguration() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.paths(PathSelectors.ant("/abc/def/pqr/"))
.build()
}
But even after writing it, this API is not exposing to swagger2. Wherever, I can understand the problem I thing that there is some problem in PathSelectors.ant("/abc/def/pqr/") . So, please someone can help me then it's better for me.
Thanks in advance...
Try this
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select() .apis(RequestHandlerSelectors.basePackage("your.base.package"))
.paths(regex("/product.*"))
.build();
}
}

Why Swagger not showing all methods in same class?

i'm trying to use swagger with my code , but not all methods are listing in swagger-ui some methods not show
i am using swagger 2.5.0 version ,and spring boot 2.1.0.RELEASE
my user rest controller
#RestController
#RequestMapping(value = "/rest")
public class UserRestController {
#Autowired
private UserService userService;
#RequestMapping(method = RequestMethod.GET, value = "/users")
public Iterator<User> getUsers() {
return userService.getUsers();
}
#RequestMapping(method = RequestMethod.GET, value = "/user/{id}")
public User getUser(#PathVariable("id") Long id) {
return userService.getUser(id);
}
#RequestMapping(method = RequestMethod.POST, value = "/user")
public User save(#RequestBody User user) {
User userValidation = userService.getUser(user.getId());
if (userValidation != null) {
throw new IllegalAddException("username already used !");
}
return userService.save(user);
}
#RequestMapping(method = RequestMethod.DELETE, value = "/user")
public User delete(#RequestBody User user) {
return userService.save(user);
}
}
and this my config code
#Configuration
#EnableSwagger2
public class SwaggerApi {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.social.core.rest")).paths(PathSelectors.ant("/rest/*"))
.build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo("Social API", "Soccial api for gamerz zone.", "API TOS", "Terms of service",
new Contact("yali", "www.social.com", "prg#gmail.com"), "License of API",
"API license URL");
}
}
getUser method not showing in swagger ui , and the method worked when i hit url and already getting data
just three method are showing
I solved this issue by adding more star in paths with me config
paths(PathSelectors.ant("/rest/**"))

From swagger editor able to get the JWT auth token, but from application which enabled swagger-ui using springfox is not working

Tested my auth server from swagger editor and is working fine. I'm able to get the token and authorization is happening without any issues. But, when I tried to integrate it with my web service where swagger UI is enabled using springfox dependencies is not working.
Success form swagger editor
Failed from application
Noticed that in the failed case, swagger UI is sending only a single POST request, but swagger editor had an OPTIONS & POST request to get the token.
Suspected CROS filter initially, so I took my swagger json and tested in swagger editor and it worked.
My auth server and resource server with application is also working fine when tested via curl.
Sample auth server and resource server is this:- https://github.com/ranjithap7576/OAuth2-JWT
And swagger configuration is below
#Configuration
#EnableSwagger2
public class SwaggerConfigNew {
#Value("${security.jwt.resource-ids}")
private String clientId;
#Value("${security.signing-key}")
private String clientSecret;
#Value("${security.oauth2.authserver}")
private String authLink;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("my.package")).build().groupName("test")
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
.securitySchemes(Collections.singletonList(securitySchema()))
.securityContexts(Collections.singletonList(securityContext()));
}
private OAuth securitySchema() {
List<AuthorizationScope> authorizationScopeList = newArrayList();
authorizationScopeList.add(new AuthorizationScope("read", "read all"));
authorizationScopeList.add(new AuthorizationScope("trust", "trust all"));
authorizationScopeList.add(new AuthorizationScope("write", "access all"));
List<GrantType> grantTypes = newArrayList();
GrantType creGrant = new ResourceOwnerPasswordCredentialsGrant(authLink + "/oauth/token");
grantTypes.add(creGrant);
return new OAuth("oauth2schema", authorizationScopeList, grantTypes);
}
#Bean
UiConfiguration uiConfig() {
return new UiConfiguration("validatorUrl", // url
"none", // docExpansion => none | list
"alpha", // apiSorter => alpha
"schema", // defaultModelRendering => schema
UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, // enableJsonEditor => true | false
true, // showRequestHeaders => true | false
60000L); // requestTimeout => in milliseconds, defaults to null (uses jquery xh timeout)
}
#Bean
public SecurityConfiguration securityInfo() {
return new SecurityConfiguration(clientId, clientSecret, "", "", "", ApiKeyVehicle.HEADER, "", " ");
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.ant("/user/**"))
.build();
}
private List<SecurityReference> defaultAuth() {
final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3];
authorizationScopes[0] = new AuthorizationScope("read", "read all");
authorizationScopes[1] = new AuthorizationScope("trust", "trust all");
authorizationScopes[2] = new AuthorizationScope("write", "write all");
return Collections.singletonList(new SecurityReference("oauth2schema", authorizationScopes));
}
// #Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
I'm using springfox 2.7.0

Swagger doesn't display information about methods - SpringBoot

I have an API in Java SpringBoot and I want to document it in Swagger.
I have done the following (I only include classes that contain some code related to Swagger):
Main class
#EnableSwagger2
public class ProvisioningApiApplication {
public static void main(String[] args) {
if (AuthConfigFactory.getFactory() == null) {
AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());
}
SpringApplication.run(ProvisioningApiApplication.class, args);
}
#Bean
public Docket swaggerSpringMvcPluggin() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
#Component
#Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
enable(SerializationFeature.INDENT_OUTPUT);
}
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Provisioning API")
.version("0.0.1")
.build();
}
}
Controller
#RestController
#EnableAutoConfiguration
#CrossOrigin
public class RecursoController {
#Autowired
private Configuration configuration;
#Autowired
private TypeSpecService typeSpecService;
#Autowired
private IoTAgentService ioTAgentService;
#Autowired
private OrionService orionService;
#Autowired
private DeviceIdService deviceIdService;
#ApiOperation(value = "Put a device", nickname = "provisionDevice", tags = "Device")
#ApiResponses({
#ApiResponse(code = 200, message = "Ok", response = NewDeviceResponse.class)
})
#RequestMapping(method = RequestMethod.PUT, value = "/devices", consumes = "application/json", produces = "application/json")
public ResponseEntity<NewDeviceResponse> provisionDevice(#RequestBody NewDeviceRequest newDeviceRequest,
#RequestHeader("X-Auth-Token") String oAuthToken) {
// what my method does
}
The documentation results in the following swagger.json file:
{
swagger: "2.0",
info: {
version: "0.0.1",
title: "Provisioning API"
},
host: "localhost:8080",
basePath: "/"
}
As you can see, it only contains the name and the version of API but not the provisionDevice method.
I've tried everything but I can't figure it out what I'm doing bad. What am I missing?
Did you add #Api annotation in your class, where you have your main services?

Resources